Dart 语法速查表 - Dart 常用语法与 Flutter 开发大全

这套速查给写 Flutter 应用或 Dart 后端的开发者,围绕每天都写的语法:空安全变量(final/const 与 late 之分)、函数与闭包、带混入(mixin)的类,以及 Future/async/await 异步流程。与平铺的 Dart 特性表不同,条目按语言构造分组,并专门点出从 Java/JS 过来的人容易踩的空安全行为。读完应能写出不带散落非空断言的空安全链、用 mixin 组合类能力,并用 Future 和 async/await 处理异步而不阻塞 UI 线程。

编程语言·共 43 条命令·最后更新 2026-07-21
dartflutter移动开发

变量与类型 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 实现多继承的方式,适合复用代码。

官方参考来源

下方为命令对应的官方权威文档,供你核对最新用法与深入查阅。

由 巧匠 维护

公开更新于 2026年7月21日,内容持续校对官方文档。

联系我们

命令或描述有误?提交反馈、商务合作或产品建议都可发送邮件给我们。

联系我们