更新
从 Dart 2.12 开始,required 关键字替换了 @required meta 注释。有关详细信息,请查看official FAQ。以下答案已更新以反映此安全性和 null 安全性。
默认需要的参数
类构造函数或函数的参数默认是必需的。
class Test {
final String x;
Test(this.x);
}
你不能这样做:
final value = Test();
// 1 positional argument(s) expected, but 0 found.
你必须这样做:
final value = Test('hello');
可选的命名参数
但是,如果用花括号将参数括起来,除了成为命名参数之外,它还成为可选参数。
由于它是可选的,因此该属性必须可以为空,如下所示:
class Test {
final String? x;
Test({this.x});
}
或者它必须有一个像这样的默认值:
class Test {
final String? x;
Test({this.x = ''});
}
所以现在可以了:
final value = Test();
这是这样的:
final value = Test(x: 'hello');
必需的命名参数
有时您不想让参数为null,并且没有自然的默认变量。在这种情况下,您可以在参数名称前添加 required 关键字:
class Test {
final String x;
Test({required this.x});
}
这已经不行了:
final value = Test();
// The named parameter 'x' is required, but there's no corresponding argument.
但这仍然没问题:
final value = Test(x: 'hello');