【问题标题】:I can't understand @required annotation in this code of Dart我无法理解此 Dart 代码中的 @required 注释
【发布时间】:2019-07-27 01:48:57
【问题描述】:

代码是这个类的一部分

   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 key 的使用也让我很困惑。

【问题讨论】:

标签: dart flutter


【解决方案1】:

@required 注解表示参数是必需参数(即需要将实参传递给参数)。
您可以改为创建函数参数,而不使用隐式使其成为必需的可选参数语法。

这个

 Category(
    this.name,
    this.color,
    this.iconLocation,

 )  

代替

 Category({
    Key key,
    @required this.name,
    @required this.color,
    @required this.iconLocation,
  })    

为什么将可选参数语法与@required 注解一起使用?

这样做的主要好处是可读性!它有助于将值传递给小部件字段,因为您不必猜测参数的位置。

根据Dart's Language tour

Flutter 实例创建表达式可能会变得复杂,因此小部件构造函数只使用命名参数。这使得实例创建表达式更易于阅读。

【讨论】:

    【解决方案2】:

    当您创建对象时,此关键字 @required 使其成为必需(需要)。

    Dart Language Tour

    一个函数可以有两种类型的参数:必需的和可选的。首先列出必需的参数,然后是任何可选参数。命名的可选参数也可以标记为@required。有关详细信息,请参阅下一节。

    阅读required

    【讨论】:

      猜你喜欢
      • 2015-05-22
      • 2022-06-11
      • 2011-08-28
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多