Dart 常用语法速查表

把 Dart 日常开发最常用的语法整理成速查,写 Flutter 代码时对照查。

编程语言·共 43 条命令·最后更新 2026-07-19
返回 编程语言

变量与类型 10

var name = 'Dart';
类型推导
String name = 'Dart';
显式类型
final name = 'Dart';
最终变量(运行时常量)
const pi = 3.14;
编译期常量
int? nullableInt;
可空类型
late String lateVar;
延迟初始化
dynamic anything = 42;
动态类型
List<int> numbers = [1, 2, 3];
列表
Map<String, int> ages = {'Alice': 25};
映射
Set<int> unique = {1, 2, 3};
集合

函数与闭包 6

int add(int a, int b) => a + b;
箭头函数
void greet(String name, [String? title]) { }
可选参数
void greet({required String name, int age = 0}) { }
命名参数
Function fn = (x) => x * 2;
闭包
void Function(int) callback;
函数类型
typedef Comparator<T> = int Function(T a, T b);
类型别名

类与混入 7

class Person { String name; Person(this.name); }
类与构造函数
class Student extends Person { }
继承
class Flyable mixin Fly { }
混入(mixin)
class Bird extends Animal with Flyable { }
使用混入
abstract class Shape { double area(); }
抽象类
class Singleton { static final instance = Singleton._(); Singleton._(); }
单例模式
class Immutable { final int value; const Immutable(this.value); }
不可变类

空安全 6

String? nullable;
可空声明
nullable?.length
安全调用
nullable ?? 'default'
空合并操作符
nullable!
强制非空断言
if (nullable != null) { nullable.length; }
类型提升
late String lateVar;
延迟初始化(使用前必须赋值)

异步编程 6

Future<int> fetchData() async { return 42; }
异步函数
int result = await fetchData();
等待异步结果
Stream<int> countStream() async* { yield 1; }
异步生成器
await for (var value in stream) { }
流监听
Future.wait([future1, future2]);
并行等待多个 Future
Completer<int> completer = Completer();
手动控制 Future

集合操作 8

list.where((x) => x > 5).toList()
过滤
list.map((x) => x * 2).toList()
映射
list.reduce((a, b) => a + b)
归约
list.fold(0, (sum, x) => sum + x)
折叠
list.any((x) => x > 0)
是否存在
list.every((x) => x > 0)
是否全部满足
list.sort((a, b) => a.compareTo(b))
排序
list.groupBy((x) => x.category)
分组(需导入 collection 包)

💡 提示

  • Dart 的空安全是编译期检查,尽量用 ? 和 ?? 避免运行时异常。
  • async/await 是异步编程的核心,避免阻塞 UI 线程。
  • mixin 是 Dart 实现多继承的方式,适合复用代码。