Dart 速通攻略(面向 Android 工程师)
背景:你已熟悉 Java/Kotlin/Android。本文用"对照 + 最小可用示例"的方式,快速上手 Dart(以 Dart 3 为基线)。
0. Dart 与 Kotlin/Java 思维对照
- 空安全 :与 Kotlin 类似,
T非空、T?可空;需要!断言或?.安全访问。 - 命名参数 :函数/构造器的"命名可选参数"很常用,常配合
required。 - 顶层函数/变量:无须写在类里(类似 Kotlin 顶层声明)。
- 继承/实现 :
extends继承,implements实现接口(任意类都可当作接口),mixin复用实现。 - 并发模型 :主线程 async/await 基于
Future;多线程用Isolate(与 Android Handler/Thread 不同)。 - 集合语法 :
[...]、{...}、集合展开...、条件/循环内嵌(collection if/for)。 - Dart 3 新特性 :
sealed、pattern matching、records、class modifiers。
1. 基本语法速览
dart
// 顶层函数与变量
const String appName = 'Demo';
int add(int a, int b) => a + b;
void main() {
print('Hello $appName: ${add(1, 2)}');
}
var自动推断,final只赋值一次,const编译期常量。- 字符串插值:
'Hello $name, len=${name.length}'。
2. 空安全与类型系统
dart
String? maybe; // 可空
int? parseInt(String s) => int.tryParse(s);
// 安全访问/默认值
final len = maybe?.length ?? 0;
// 非空断言(不建议滥用)
final must = maybe!;
- 泛型默认非空:
List<String>;可空为List<String>?或元素可空List<String?>。
3. 函数与参数(命名参数是关键)
dart
int sum(int a, {required int b, int c = 0}) => a + b + c;
// 调用:命名参数必须写名
final s = sum(1, b: 2, c: 3);
// 高阶函数 & tear-off
final list = [1, 2, 3];
final doubled = list.map((e) => e * 2).toList();
final prints = list.forEach(print); // 函数 tear-off
4. 类 / 构造 / 工厂 / Getter / 扩展
dart
class User {
final String id;
String name;
// 命名参数构造
User({required this.id, required this.name});
// 命名构造函数
User.empty() : id = '0', name = '';
// 工厂:可返回缓存或子类
factory User.fromMap(Map<String, dynamic> m) =>
User(id: m['id'], name: m['name'] ?? '');
String get display => '$id@$name';
set display(String value) => name = value.split('@').last;
}
// 扩展方法
extension StringX on String {
bool get isUUID => RegExp(r'^[0-9a-fA-F-]{36}$').hasMatch(this);
}
late延迟初始化,abstract抽象类,sealed密封层级,mixin复用实现。
5. 集合与语法糖(collection if/for、展开)
dart
final items = [1, 2, 3];
final plus = [0, ...items, if (items.isNotEmpty) 4, for (final e in items) e * 2];
final map = {'a': 1, 'b': 2, if (plus.length > 3) 'c': 3};
6. 模式匹配(patterns)与记录(records)
dart
// records(匿名元组)
(int x, String y) pair() => (1, 'a');
final (a, b) = pair(); // 解构
// 模式匹配
String describe(Object o) => switch (o) {
int n when n > 0 => 'positive $n',
int n => 'int $n',
String s => 'str $s',
_ => 'other',
};
7. 枚举、密封类(替代 Kotlin sealed class)
dart
enum Flavor { vanilla, chocolate }
sealed class Result {}
class Success extends Result { final String data; Success(this.data); }
class Failure extends Result { final String msg; Failure(this.msg); }
String handle(Result r) => switch (r) {
Success(data: final d) => 'ok $d',
Failure(msg: final m) => 'err $m',
};
8. 异步:Future / async-await / Stream
dart
Future<int> fetch() async {
await Future.delayed(const Duration(milliseconds: 100));
return 42;
}
// try/catch 同步写法
void demo() async {
try {
final v = await fetch();
print(v);
} catch (e, s) {
print('error $e\n$s');
}
}
// Stream
Stream<int> counter() async* {
for (var i = 0; i < 3; i++) {
yield i;
}
}
- 并行:
Future.wait([...])。 - 多线程:使用
Isolate或 Flutter 的compute(与 Android 线程模型不同)。
9. 网络 & JSON(dio + json_serializable)
dart
// pubspec.yaml 添加依赖:dio、json_annotation、build_runner、json_serializable
// 模型
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
final int id;
final String name;
User({required this.id, required this.name});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
- 生成命令:
flutter pub run build_runner build --delete-conflicting-outputs。 - Dio 使用与 Android 拦截器类似,
LogInterceptor可直接打印请求/响应。
10. 包管理与工具链
- 包管理:
pubspec.yaml,仓库为 pub.dev。 - 常用命令:
dart format .代码格式化dart analyze静态检查dart test单元测试(Flutter 用flutter test)flutter pub get / run拉包/执行生成器
11. 测试(简述)
dart
import 'package:test/test.dart';
void main() {
test('sum', () {
expect(1 + 2, 3);
});
}
Flutter 小部件测试使用 flutter_test 与 WidgetTester。
12. 常见对照(Kotlin → Dart)
val/var→final/vardata class→ 手写== hashCode toString或用freezed(代码生成)sealed class→sealed class(Dart 3 原生支持)when→switch+ patterns?. ?: !!→?. ?? !- 扩展函数 →
extension;伴生对象 → 顶层函数/静态方法 - 协程 →
Future/async(单线程事件循环),多线程请用Isolate
13. 性能与实践建议
- 避免滥用
!非空断言;优先?.和??。 - 大 JSON 建议代码生成(
json_serializable/freezed)。 - 频繁小对象场景可用
const构造与不可变数据结构(Flutter 重建友好)。 - 复杂计算搬到
Isolate/compute,避免阻塞 UI 事件循环。
14. 进阶:模式匹配与解构的实战片段
dart
// 解构 record
final (x, y, z) = (1, 'k', true);
// 对 Map/类做匹配
String stringify(Object obj) => switch (obj) {
{'id': int id, 'name': String n} => 'user#$id $n',
User(id: final id, name: final n) => 'User($id, $n)',
_ => 'unknown'
};
15. 学习路径(建议 7 天)
- Day 1:语法速览、空安全、函数与参数、集合语法
- Day 2:类/构造/工厂/扩展、枚举/密封、运算符与 getter/setter
- Day 3:异步(Future/Stream/错误处理/并行)、Isolate/compute
- Day 4:Dio + JSON(生成器)、本地持久化(shared_preferences)
- Day 5:Dart 3 新特性(records、patterns、sealed)、lint 规则
- Day 6:测试(unit/widget)、性能与最佳实践
- Day 7:把现有 Kotlin/Java 业务迁移一小段到 Dart 演练
参考
- Dart 语言导引:
https://dart.dev/language - 异步编程(Future/Stream):
https://dart.dev/codelabs/async-await - 包与发布:
https://dart.dev/tools/pub - Flutter/Dart 最佳实践(社区文章与官方文档)