代码是此类的一部分
class Category extends StatelessWidget {
final String name;
final ColorSwatch color;
final IconData iconLocation;
而必填项的使用是这样的:
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键也使我感到困惑。
答案 0 :(得分:2)
@required
批注指示该参数是必需的参数(即,必须将参数传递给该参数)。
相反,您可以创建函数参数,而无需使用可选参数语法(隐式使其成为必需参数)。
即此
Category(
this.name,
this.color,
this.iconLocation,
)
代替
Category({
Key key,
@required this.name,
@required this.color,
@required this.iconLocation,
})
为什么将可选参数语法与@required注释一起使用?
这样做的主要好处是可读性!当您将值传递到窗口小部件字段时,它很有用,因为您不必猜测参数的位置。
Flutter实例创建表达式可能会变得很复杂,因此小部件构造函数仅使用命名参数。这使实例创建表达式更易于阅读。
答案 1 :(得分:0)
在创建对象时,此关键字@required
是必需的。
一个函数可以有两种类型的参数:必需和可选。首先列出必需的参数,然后列出所有可选参数。命名的可选参数也可以标记为@required。有关详细信息,请参见下一部分。
了解required