飞镖的构造者

时间:2018-05-19 18:40:05

标签: dart flutter

我班上有这个构造函数。现在,当它是这样的时候,我得到

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);

这是一个错误。

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

这是什么意思?

3 个答案:

答案 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可选参数。

命名为可选参数{}

  1. 用于省略/避免参数和可读性。
  2. 参数位置无关紧要,因为请使用名称。
  3. 由于您可以避免参数,因此要表示此参数是必需的,请使用@required。大多数时候这个注释用来说这是无法避免的(如通知)。
  4. 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),
    

    位置可选参数[]

    1. 也用于避免或省略args。
    2. 由于没有可读性而无法提及名称(作为布尔参数的示例)。
    3. 论点立场很重要。
    4. 不需要@required,因为我们必须提供参数。
    5. const Category(
          this.name,
          this.icon,
          this.color
        ) : assert(name != null),
            assert(icon != null),
            assert(color != null);
      
      //Category(_categoryName, _categoryIcon, _categoryColor),
      

      Read more from this SO answer

答案 2 :(得分:1)

@required提示某些值应作为参数传递给此参数,即使它只是默认值。

这个提示只有在与可选参数一起使用时才有意义,例如当你用大括号括起参数时,因为否则参数是强制性的(就像你在例如java中所习惯的那样。

这里的命名有点不幸但是dart中的named参数也意味着它们是可选的,你可以调用一个没有它们的函数。