1. Hello World
dart
void main() {
print('Hello, World!');
}
2. Variables and Constants
变量和常量定义
dart
// 自动推断类型
var name = 'Bob';
int age = 20;
double height = 1.80;
bool isStudent = true;
// const 常量 不能修改 在编译时就确定
const String ID = "123456";
// final 只能赋值一次 但是可以在运行时确定
final DateTime now = DateTime.now();
print('name: $name, age: $age, height: $height, isStudent: $isStudent');
// name: Bob, age: 20, height: 1.8, isStudent: true
print("ID: ${ID}");
// ID: 123456
print("now: ${now}");
// now: 2021-08-25 10:37:44.387928
变量空值
dart
// ? is used to declare a variable as nullable variable
// ? 可以用来声明一个变量可为空变量
int? age;
print(age); // null
age = 20;
print(age); // 20
3. 内置类型
Number
dart
int age = 20;
double height = 1.80;
print(age); // 20
print(height); // 1.8
// int can be assigned to double but not vice versa
height = 1;
print(height); // 1.0
// int to double
double newHeight = age.toDouble();
print(newHeight); // 20.0
// double to int
int newAge = height.toInt();
print(newAge); // 1
const _NaN = 0 / 0;
print(_NaN.isNaN); // true
print(_NaN is double); // true
print(_NaN is int); // false
Boolean
dart
bool isStudent = true;
print(isStudent); // true
const count = 0;
// Error: Conditions must have a static type of 'bool'. No implicit casts are allowed.
if (count) {
print('count is true');
}
String
dart
String name = 'Bob';
String message = 'Hello, $name';
print(message); // Hello, Bob
String multiLine = '''
Hello,
$name
''';
print(multiLine);
// Hello,
// Bob
List
dart
List<int> numbers = [1, 2, 3, 4, 5];
print(numbers); // [1, 2, 3, 4, 5]
List<String> names = ['Bob', 'Alice', 'John'];
print(names); // [Bob, Alice, John]
names.add('Tom');
print(names); // [Bob, Alice, John, Tom]
for (var name in names) {
print(name);
}
Set
dart
Set<int> numbers = {1, 2, 3, 4, 5};
var nums = new Set<int>();
print(numbers); // {1, 2, 3, 4, 5}
numbers.add(6);
numbers.add(6);
numbers.contains(6); // true
print(numbers); // {1, 2, 3, 4, 5, 6}
var objs = new Set<dynamic>();
objs.add("Hello");
objs.add("HuTu");
final strs = objs.cast<String>();
strs.forEach((element) {
print(element+'s');
});
Map
dart
Map<String, int> scores = {
'Alice': 100,
'Bob': 90,
'John': 80
};
print(scores); // {Alice: 100, Bob: 90, John: 80}
scores['Tom'] = 70;
print(scores); // {Alice: 100, Bob: 90, John: 80, Tom: 70}
scores.remove('Tom');
print(scores); // {Alice: 100, Bob: 90, John: 80}
for (var key in scores.keys) {
print('$key: ${scores[key]}');
}
Dynamic
dart
dynamic name = 'Bob';
print(name); // Bob
name = 20;
print(name); // 20
var age = 20 * name as int;
print(age); // 400
Object
dart
Object name = '123';
print(name);
Runes
dart
String name = 'Bob';
print(name.runes.toList()); // (66, 111, 98)
print(name.codeUnits); // [66, 111, 98]
Runes input = new Runes('\u{1f605}');
print(input); // (128517)
print(new String.fromCharCodes(input)); // 😅
Symbols
dart
Symbol name = #name;
print(name); // Symbol("name")
// Convert Symbol to String
print(name.toString()); // "Symbol("name")"
// Convert Symbol to String
print(name
.toString()
.replaceAll('Symbol("', '')
.replaceAll('")', '')); // "name"
// Symbol usages cases
var person = {
#name: 'John',
#age: 30,
};
print(person[#name]); // John
print(person[#age]); // 30
用于反射
dart
import 'dart:mirrors';
class MyClass {
void sayHello(String name) {
print('Hello, $name!');
}
}
void main() {
MyClass myInstance = MyClass();
InstanceMirror im = reflect(myInstance);
// 使用符号调用sayHello方法
im.invoke(#sayHello, ['World']);
}
Type
dart
Type type = String;
print(type); // String
print(type.runtimeType); // Type
print(type is Type); // true
print(type is String); // false
print(type is Object); // true
print(type is dynamic); // true
print(type is int); // false
获取类型
dart
void main() {
var list = [1, 2, 3];
printType(list);
var string = "Hello, Dart!";
printType(string);
}
void printType(dynamic obj) {
Type type = obj.runtimeType;
print("The type of the object is $type");
}
Enum
dart
enum Color { red, green, blue }
void main() {
print(Color.red); // Color.red
print(Color.red.index); // 0
print(Color.values); // [Color.red, Color.green, Color.blue]
}
4. Operators
Arithmetic Operators
dart
int a = 11;
print(a ~/ 2); // 5
print(a % 2); // 1
print(a++); // 11
print(a); // 12
print(++a); // 13
print(a); // 13
5. 自定义类操作符
dart
class Point {
int x, y;
Point(this.x, this.y);
Point operator +(Point p) {
return new Point(x + p.x, y + p.y);
}
Point operator *(int n) {
return Point(x * n, y * n);
}
Point operator /(int n) {
return Point(x ~/ n, y ~/ n);
}
Point operator -() {
return Point(-x, -y);
}
Point operator -(Point p) {
return Point(x - p.x, y - p.y);
}
@override
String toString() {
return 'Point($x, $y)';
}
}
void main() {
Point p1 = Point(10, 20);
Point p2 = Point(30, 40);
print(p1 + p2); // Point(40, 60)
print(p1 * 2); // Point(20, 40)
print(p1 / 2); // Point(5, 10)
print(-p1); // Point(-10, -20)
Point p3 = p1 - p2;
print(p3); // Point(-20, -20)
}
6. Functions
Function Definition
dart
void main() {
print(sayHello('Bob')); // Hello, Bob!
print(sayHello2('Alice')); // Hello, Alice!
print(sayHello3('John')); // Hello, John!
}
String sayHello(String name) {
return 'Hello, $name!';
}
final sayHello2 = (String name) => 'Hello, $name!';
sayHello3(String name) => 'Hello, $name!';
Optional Parameters
dart
void main() {
print(sayHello('Bob')); // Hello, Bob!
print(sayHello('Alice', 'Good Morning')); // Good Morning, Alice!
print(sayHello('John', 'Good Afternoon', 'How are you?')); // Good Afternoon, John! How are you?
}
String sayHello(String name, [String? greeting, String? message]) {
if (greeting != null && message != null) {
return '$greeting $name! $message';
} else if (greeting != null) {
return '$greeting $name!';
} else {
return 'Hello, $name!';
}
}
Named Parameters
dart
void main() {
print(sayHello('Bob')); // Hello, Bob!
print(sayHello('Alice', greeting: 'Good Morning')); // Good Morning, Alice!
print(sayHello('John', greeting: 'Good Afternoon', message: 'How are you?')); // Good Afternoon, John! How are you?
}
String sayHello(String name, {String? greeting, String? message}) {
if (greeting != null && message != null) {
return '$greeting $name! $message';
} else if (greeting != null) {
return '$greeting $name!';
} else {
return 'Hello, $name!';
}
}
Default Parameters
dart
sayHello(
{String name = 'Anonymous',
String greeting = 'Hello',
String message = 'Are you fine?'}) {
return '$greeting $name! $message';
}
void main() {
print(sayHello());
print(sayHello(name: 'John', greeting: 'Hi', message: 'How are you?'));
}
Function as a Parameter
dart
void main() {
print(sayHello('Bob', (name) => 'Hello, $name!'));
print(sayHello('Alice', (name) => 'Good Morning, $name!'));
print(sayHello('John', (name) => 'Good Afternoon, $name!'));
}
String sayHello(String name, String Function(String) greeting) {
return greeting(name);
}
Function as a Return Type
dart
void main() {
var greeting = sayHello('Bob');
print(greeting('Hello'));
}
Function sayHello(String name) {
return (String message) => '$message' + ' ' + name;
}
Anonymous Function
dart
void main() {
var list = ['Bob', 'Alice', 'John'];
list.forEach((name) {
print('Hello, $name!');
});
}
Closures
dart
Function makeAdder(int addBy) {
return (int i) => addBy + i;
}
void main() {
var add2 = makeAdder(2);
var add4 = makeAdder(4);
print(add2(3)); // 5
print(add4(3)); // 7
}
7. Cascade Operator
dart
class Person {
String? name;
int age = 0;
String? address;
void show() {
print('name: $name, age: $age, address: $address');
}
}
void main() {
var person = Person()
..name = 'Bob'
..age = 20
..address = 'New York';
person.show();
}
8. Control Flow
switch case
dart
void main() {
var grade = 'A';
switch (grade) {
case 'A':
print('Excellent');
break;
case 'B':
print('Good');
break;
case 'C':
print('Fair');
break;
case 'D':
print('Poor');
break;
default:
print('Invalid grade');
}
}
9. Loops
for loop
dart
void main() {
var numbers = [1, 2, 3, 4, 5];
for (var number in numbers) {
print(number);
}
}
while loop
dart
void main() {
var count = 0;
while (count < 5) {
print(count);
count++;
}
}
do while loop
dart
void main() {
var count = 0;
do {
print(count);
count++;
} while (count < 5);
}
for i loop
dart
void main() {
for (var i = 0; i < 5; i++) {
print(i);
}
}
10. Exception Handling
throw exception
dart
void main() {
var age = 20;
if (age < 18) {
throw Exception('Age must be greater than 18');
} else {
print('You are eligible to vote');
}
}
try catch
dart
void main() {
var age = 2;
try {
if (age < 18) {
throw "You are not eligible to vote";
} else {
print('You are eligible to vote');
}
} on String catch (e) {
print("---- String Exception ---- $e");
} catch (e) {
print(e);
} finally {
print('Thank you');
}
}
11. Generics
dart
class Data<T> {
T value;
Data(this.value);
T getValue() {
return value;
}
}
void main() {
var data = Data<int>(10);
print(data.getValue()); // 10
var data2 = Data<String>('Hello, Dart!');
print(data2.getValue()); // Hello, Dart!
}
12. Future
future 是一个异步操作的结果,它会在未来的某个时间点返回一个值。
dart
Future<String> fetchData() {
return Future.delayed(Duration(seconds: 2), () {
return "Hello, Dart!";
});
}
void main() {
print('Fetching data...');
fetchData().then((value) {
print(value);
});
print('Data fetched');
}
13. Async Await
dart
Future<String> fetchData() {
return Future.delayed(Duration(seconds: 2), () {
return "Hello, Dart!";
});
}
void main() async {
print('Fetching data...');
var data = await fetchData();
print(data);
print('Data fetched');
}
14. Abstract Class
dart
abstract class Animal {
void makeSound();
}
class Dog extends Animal {
@override
void makeSound() {
print('Bark');
}
}
class Cat extends
Animal {
@override
void makeSound() {
print('Meow');
}
}
void main() {
var dog = Dog();
dog.makeSound(); // Bark
var cat = Cat();
cat.makeSound(); // Meow
}
15. Interface
接口是一种规范,它定义了类应该实现的方法。
dart
class Animal {
void makeSound() {
print('Animal makes a sound');
}
}
class Dog implements Animal {
@override
void makeSound() {
print('Bark');
}
}
class Cat implements Animal {
@override
void makeSound() {
print('Meow');
}
}
void main() {
var dog = Dog();
dog.makeSound(); // Bark
var cat = Cat();
cat.makeSound(); // Meow
}
16. Extend Class
dart
class Animal {
void makeSound() {
print('Animal makes a sound');
}
}
class Dog extends Animal {
void bark() {
print('Bark');
}
}
class Cat extends Animal {
void meow() {
print('Meow');
}
}
void main() {
var dog = Dog();
dog.makeSound(); // Animal makes a sound
dog.bark(); // Bark
var cat = Cat();
cat.makeSound(); // Animal makes a sound
cat.meow(); // Meow
}
17. Mixin
dart
mixin Swim {
void swim() {
print('Swimming');
}
}
mixin Fly {
void fly() {
print('Flying');
}
}
class Animal {
void makeSound() {
print('Animal makes a sound');
}
}
class Fish extends Animal with Swim {
void swim() {
print('Fish is swimming');
}
}
class Bird extends Animal with Fly {
void fly() {
print('Bird is flying');
}
}
class Duck extends Animal with Swim, Fly {
sayHello() {
print('Hello');
}
}
void main() {
var fish = Fish();
fish.makeSound(); // Animal makes a sound
fish.swim(); // Fish is swimming
var bird = Bird();
bird.makeSound(); // Animal makes a sound
bird.fly(); // Bird is flying
var duck = Duck();
duck.makeSound(); // Animal makes a sound
duck.swim(); // Swimming
duck.fly(); // Flying
duck.sayHello(); // Hello
}
18. Library
Import Library
dart
import 'dart:math';
void main() {
print(min(10, 20)); // 10
print(max(10, 20)); // 20
}
import Netwrok Library
dart
import 'https://pub.dev/packages/http' as http;
void main() {
var url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
http.get(url).then((response) {
print(response.statusCode);
print(response.body);
});
}
split library
part 用于将一个大的库文件分割成多个小的库文件。
dart
library my_library;
part 'part1.dart';
part 'part2.dart';