我班上有这个构造函数。现在,当它是这样的时候,我得到
DebuggerDisplayAttribute
-
The type parameter icon is annotated with @required
but only named parameters without default value can be annotated with it.
当像这样调用构造函数时:
const Category(
@required this.name,
@required this.icon,
@required this.color
) : assert(name != null),
assert(icon != null),
assert(color != null);
这是一个错误。
当我用{}包围我的构造函数参数时,所有这些都消失了。
这是什么意思?
答案 0 :(得分:8)
{}
使它们成为命名参数
const Category({
@required this.name,
@required this.icon,
@required this.color
}) : assert(name != null),
assert(icon != null),
assert(color != null);
或只是删除@required
没有{}
它们是无论如何都需要的位置参数。
Category('foo', someIcon, Colors.white)
VS
Category(name: 'foo', icon: someIcon, color: Colors.white)
[]
使它们成为可选的位置参数。
需要首先声明位置(非可选),最后可选参数。
可选的位置和可选命名参数不能一起使用。
可选参数(位置和命名)可以具有默认值
this.name = 'foo'
默认值需要是编译时常量。
答案 1 :(得分:3)
您已使用命名的可选arguemnts但您的构造函数接受postional可选参数。
{}
:@required
。大多数时候这个注释用来说这是无法避免的(如通知)。const Category({
@required this.name,
@required this.icon,
@required this.color
}) : assert(name != null),
assert(icon != null),
assert(color != null);
//Category(name: _categoryName, icon: _categoryIcon, color: _categoryColor),
[]
:@required
,因为我们必须提供参数。const Category(
this.name,
this.icon,
this.color
) : assert(name != null),
assert(icon != null),
assert(color != null);
//Category(_categoryName, _categoryIcon, _categoryColor),
答案 2 :(得分:1)
@required
提示某些值应作为参数传递给此参数,即使它只是默认值。
这个提示只有在与可选参数一起使用时才有意义,例如当你用大括号括起参数时,因为否则参数是强制性的(就像你在例如java中所习惯的那样。
这里的命名有点不幸但是dart中的named
参数也意味着它们是可选的,你可以调用一个没有它们的函数。