我无法理解这段 Dart 代码中的 @required 注释

jsd*_*ell 5 dart flutter

代码是这个类的一部分

   class Category extends StatelessWidget {

      final String name;
      final ColorSwatch color;
      final IconData iconLocation;
Run Code Online (Sandbox Code Playgroud)

使用 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);
Run Code Online (Sandbox Code Playgroud)

Key 键的使用也让我感到困惑。

non*_*hto 16

@required注释表明该参数是必需参数(即需要向该参数传递一个实参)。
您可以创建函数参数,而不使用可选参数语法,这隐式使其成为必需参数。

即这个

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

 )  
Run Code Online (Sandbox Code Playgroud)

代替

 Category({
    Key key,
    @required this.name,
    @required this.color,
    @required this.iconLocation,
  })    
Run Code Online (Sandbox Code Playgroud)

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

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

根据Dart 的语言之旅

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