flutter - Dart 中的空安全

标签 flutter oop dart dart-null-safety

最近 dart 发布了名为 null safety 的新功能。我对如何创建带有命名参数的构造函数有点困惑。当我遵循花括号的使用时,出现错误。

这是我的代码:

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

这是我得到的错误: enter image description here

最佳答案

由于类的属性不可为空(例如,类型是 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,
    });

关于flutter - Dart 中的空安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68653716/

相关文章:

dart - 具有水平列表和网格的 Flutter 可滚动主体作为子项

python - 为什么这个 python 类实例是可哈希的?

dart - 角 Dart 中的嵌套路径

flutter - 我如何创建一个可缩放的页面,如带有 flutter 的 map

flutter - 如何在Flutter中恢复最后一条路线

php - 在 PHP 中从用户输入自动加载所需的类

php - 类似于 CLOS 的 PHP 对象模型

file - 与其他应用程序共享文件/文本并成功回调

flutter - 如何在隔离中加载和解析Json?

flutter - Flutter中的TextFormField验证