飞镖的构造者

MAA*_*MAA 10 dart flutter

我班上有这个构造函数.现在,就像这样,我明白了

The type parameter icon is annotated with @required
but only named parameters without default value can be annotated with it.
Run Code Online (Sandbox Code Playgroud)

-

const Category(
    @required this.name,
    @required this.icon,
    @required this.color
  ) : assert(name != null),
      assert(icon != null),
      assert(color != null);
Run Code Online (Sandbox Code Playgroud)

当像这样调用构造函数时:

        Category(name: _categoryName, icon: _categoryIcon, color: _categoryColor),
Run Code Online (Sandbox Code Playgroud)

这是一个错误.

当我用{}包围构造函数参数时,所有这些都消失了.

这是什么意思?

Gün*_*uer 15

{} 缺少使其成为命名参数

const Category({
    @required this.name,
    @required this.icon,
    @required this.color
  }) : assert(name != null),
      assert(icon != null),
      assert(color != null);
Run Code Online (Sandbox Code Playgroud)

或只是删除 @required

没有{}它们,无论如何都是位置参数。

Category('foo', someIcon, Colors.white)
Run Code Online (Sandbox Code Playgroud)

Category(name: 'foo', icon: someIcon, color: Colors.white)
Run Code Online (Sandbox Code Playgroud)

[] 使它们成为可选的位置参数。

首先需要声明位置(非可选),最后是可选参数。

可选的位置参数和可选的命名参数不能一起使用。

可选参数(位置参数和命名参数)可以具有默认值

this.name = 'foo'
Run Code Online (Sandbox Code Playgroud)

默认值必须是编译时常量。


Bla*_*nka 7

您使用了命名的可选参数,但您的构造函数接受了位置可选参数。

命名可选参数{}

  1. 用于省略/避免参数和可读性。
  2. 参数位置无关紧要,因为使用名称引用。
  3. 由于您可以避免使用该参数,因此要表示此参数是必需的,请使用@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),
Run Code Online (Sandbox Code Playgroud)

位置可选参数[]

  1. 也用于避免或省略 args。
  2. 无法提及名称,因为没有可读性(作为布尔参数的示例)。
  3. 参数位置很重要。
  4. 不需要,@required因为我们必须提供参数。

const Category(
    this.name,
    this.icon,
    this.color
  ) : assert(name != null),
      assert(icon != null),
      assert(color != null);

//Category(_categoryName, _categoryIcon, _categoryColor),
Run Code Online (Sandbox Code Playgroud)

从这个 SO 答案中阅读更多内容