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