【问题标题】:Null Safety in DartDart 中的空安全性
【发布时间】:2021-10-09 16:52:39
【问题描述】:

最近 dart 发布了名为 null 安全的新功能。我对如何使用命名参数创建构造函数有点困惑。当我使用花括号时,我得到一个错误。

这是我的代码:

void main() {
  
}

class Student {
  String name = '';
  num age = 0;
  List<num> marks = [];
  
  Student({
    this.name,
    this.age,
    this.marks
    });
  
  void printStudentDetails() {
    print('Student Name: ' + this.name);
  }
}

这是我得到的错误:

【问题讨论】:

    标签: flutter oop dart dart-null-safety


    【解决方案1】:

    由于您的类的属性不可为空(例如,类型是 String 而不是 String?),您要么需要在构造函数的属性中添加 required,要么提供一个默认值(这似乎做你想做的事)。

      Student({
        this.name = '',
        this.age = 0,
        this.marks = [],
        });
    

    您现在也可以将您的属性设置为最终属性:

    final String name;
    final num age;
    final List<num> marks;
    

    或者,使用必需的关键字:

      Student({
        required this.name,
        required this.age,
        required this.marks,
        });
    

    【讨论】:

      猜你喜欢
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 2020-05-20
      • 2021-03-21
      • 1970-01-01
      相关资源
      最近更新 更多