Dart 速通攻略(面向 Android 工程师)

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 新特性sealedpattern matchingrecordsclass 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_testWidgetTester


12. 常见对照(Kotlin → Dart)

  • val/varfinal/var
  • data class → 手写 == hashCode toString 或用 freezed(代码生成)
  • sealed classsealed class(Dart 3 原生支持)
  • whenswitch + 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 最佳实践(社区文章与官方文档)

相关推荐
Frank_HarmonyOS1 小时前
MVI模式
android
m***9821 小时前
Redis6.2.6下载和安装
android·前端·后端
未来之窗软件服务1 小时前
幽冥大陆(三十九)php二维数组去重——东方仙盟筑基期
android·开发语言·算法·php·仙盟创梦ide·东方仙盟·东方仙盟sdk
w***4242 小时前
【mysql部署】在ubuntu22.04上安装和配置mysql教程
android·mysql·adb
e***75392 小时前
MySQL错误-this is incompatible with sql_mode=only_full_group_by完美解决方案
android·sql·mysql
道路与代码之旅2 小时前
“变量也能是函数?——论 Kotlin 中那些会说话的变量,以及它们如何让代码少说废话”
android·开发语言·kotlin
x***01062 小时前
Mysql之主从复制
android·数据库·mysql
千里马学框架2 小时前
wms开发常用调试开发技巧之WMShell的实用命令
android·framework·wms·安卓framework开发·systemui·proto·wmshell
龙之叶3 小时前
MT8766平台Android 12系统ESIM功能实现指南
android