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

标签 dart flutter

代码是这个类的一部分

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

最佳答案

@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 instance creation expressions can get complex, so widget constructors use named parameters exclusively. This makes instance creation expressions easier to read.

关于dart - 我无法理解这段 Dart 代码中的 @required 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55005437/

相关文章:

ios - Flutter TextField Ipad中文输入法,选择始终放在最前面

flutter - 带回来后隐藏顶部状态栏

dart - 如何从 flutter (charts_flutter)在饼图上添加图例?

oop - 由于该方法仅在 “if” block 中返回,为什么没有编译错误?

web - Flutter Web - 如何重新加载当前事件页面

android - 在 Flutter 中显示 100 张或更多图像的最快方法

android - 如何在 Flutter 中检索没有文本字段的文本输入

android - 有没有办法在 flutter charts_flutter : ^0. 8.1 中垂直放置标签文本

flutter - flutter JSON解析映射

json - _TypeError(类型 'List<dynamic>'不是类型 'Map<String, dynamic>'的子类型)