Flutter 中的点简写
了解如何使用 Dart 的点简写编写更简洁、更清爽的 Flutter 代码。
点简写(dot shorthands)特性允许你在访问静态成员、构造函数或枚举值时省略显式类型,前提是编译器能从周围上下文推断出类型。
为什么点简写很重要
#在 Flutter 中构建布局通常涉及深度嵌套的 widget 树。以往这意味着需要为颜色、排版、对齐等属性反复输入显式的类和枚举名称。点简写减少了这类样板代码,让你的代码更易读、写得更快。
下面是通过构建一个简单的 Container 进行的并排对比:
不使用点简写
#Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Hello World',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
],
),
);
使用点简写
#Container(
alignment: .center, // Instead of Alignment.center,
padding: const .all(16.0), // Instead of EdgeInsets.all(16.0)
child: Column(
mainAxisAlignment: .center, // Instead of MainAxisAlignment.center
crossAxisAlignment: .start, // Instead of CrossAxisAlignment.start
children: [
Text(
'Hello World',
style: TextStyle(
fontWeight: .bold, // Instead of FontWeight.bold
),
),
],
),
);
在哪里使用点简写
#只要 Dart 编译器有明确的「上下文类型」(context type),即它确切知道期望的类型,点简写就可以使用。在 Flutter 中,这几乎适用于 widget 属性列表内的所有位置。
在 Flutter 中,点简写最常见的目标包括:
-
Enums:
MainAxisAlignment,CrossAxisAlignment,BoxFit,TextDirection. -
枚举:
MainAxisAlignment、CrossAxisAlignment、BoxFit、TextDirection。 -
Static properties and methods:
FontWeight(constants like.bold). 静态属性和方法:
FontWeight(如.bold等常量)。-
Constructors:
EdgeInsets.all(),BorderRadius.circular(). 构造函数:
EdgeInsets.all()、BorderRadius.circular()。
示例:枚举
#当某个属性期望 enum 类型(例如 mainAxisAlignment)时,你可以省略枚举名,只提供以点(.)开头的值:
Row(
mainAxisAlignment: .spaceEvenly, // Infers MainAxisAlignment.spaceEvenly
children: [ /* ... */ ],
)
示例:静态属性
#当上下文类型恰好是定义该属性的类时,静态属性即可使用点简写。常见示例是用 FontWeight 设置文本样式:
Text(
'Feature highlights',
style: TextStyle(
fontWeight: .bold, // Infers FontWeight.bold
),
)
示例:构造函数
#
你也可以对命名构造函数使用点简写。许多 Flutter 布局属性接受 EdgeInsetsGeometry 等基类。为支持点简写,Flutter 在这些基类上添加了重定向构造函数,指向相应的子类。
Padding(
padding: .symmetric(horizontal: 16.0, vertical: 8.0), // Infers EdgeInsetsGeometry.symmetric
child: Text('Spaced out text'),
)
你甚至可以使用 .new 调用未命名构造函数,不过在标准 widget 树中较少见:
class _MyState extends State<MyWidget> {
final ScrollController _scrollController = .new(); // Infers ScrollController()
// ...
}
除非另有说明,本文档之所提及适用于 Flutter 3.44.0 版本。本页面最后更新时间:2026-06-04。查看文档源码 或者 为本页面内容提出建议。