Dart语言速查
变量与类型
// 类型推断
var name = 'Alice'; // String
var age = 28; // int
final pi = 3.14; // 不可变
const maxSize = 100; // 编译时常量
// 空安全
String? nullable = null; // 可空类型
String nonNull = 'hi'; // 非空类型
String name2 = nullable ?? 'default'; // null coalescing
String name3 = nullable!; // 强制解包
集合
// List
var list = [1, 2, 3];
list.add(4);
list.where((n) => n > 2).toList(); // [3, 4]
// Map
var map = {'key': 'value', 'num': 42};
map['newKey'] = 'new';
// Set
var set = {1, 2, 3, 2}; // {1, 2, 3}
// Spread operator
var merged = [...list, ...['a', 'b']];
// Collection if/for
var evens = [for (var i = 1; i <= 10; i++) if (i.isEven) i];
异步编程
// Future 异步
Future fetchUser(int id) async {
final response = await http.get(Uri.parse('/users/$id'));
return response.body;
}
// Stream 流
Stream countDown(int from) async* {
for (int i = from; i >= 0; i--) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
// 错误处理
try {
final data = await fetchUser(1);
} on HttpException catch (e) {
print('HTTP error: $e');
} catch (e, stack) {
print('Error: $e\n$stack');
}
类
class Animal {
final String name;
int _age; // 私有字段
Animal(this.name, this._age); // 命名构造参数
Animal.kitten(String name) : this(name, 0); // 命名构造函数
int get age => _age;
set age(int v) => _age = v > 0 ? v : 0;
@override
String toString() => 'Animal($name, age=$_age)';
}
class Dog extends Animal {
String breed;
Dog(String name, int age, this.breed) : super(name, age);
void bark() => print('Woof!');
}
pubspec.yaml 示例
name: my_app
description: 示例 Dart 应用
version: 1.0.0
environment:
sdk: '>=3.0.0 <4.0.0'
dependencies:
http: ^1.1.0
json_serializable: ^6.7.0
dev_dependencies:
test: ^1.24.0
lints: ^3.0.0