代码是这个类的一部分
class Category extends StatelessWidget {
final String name;
final ColorSwatch color;
final IconData iconLocation;
required 的用法是这样的:
const Category({
Key key,
@required this.name,
@required this.color,
@required this.iconLocation,
}) : assert(name != null),
assert(color != null),
assert(iconLocation != null),
super(key: key);
Key键的使用也让我很困惑。
最佳答案
@required
注解表示该参数是必填参数(即参数需要传递给参数)。
您可以创建函数参数而不使用隐式使其成为必需的可选参数语法。
即这个
Category(
this.name,
this.color,
this.iconLocation,
)
代替
Category({
Key key,
@required this.name,
@required this.color,
@required this.iconLocation,
})
为什么将可选参数语法与@required 注释一起使用?
这样做的主要好处是可读性!它有助于将值传递给您的小部件字段,因为您不必猜测参数的位置。
Flutter instance creation expressions can get complex, so widget constructors use named parameters exclusively. This makes instance creation expressions easier to read.
关于dart - 我无法理解这段 Dart 代码中的 @required 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55005437/