[英]Right way of using optional named parameters in Dart class constructor
[英]Optional Arguments in dart class constructor
为什么在尝试构造我的构造函数时出现错误我想要一个命名参数但不是必需的我如何解决这个问题
class Task {
int id;
String title;
String description;
**Task({this.id , this.title , this.description}); // Giving me Errors here**
Map<String , dynamic> toMap()
{
return {
'id' : id,
'title' : title,
'description' : description,
};
}
@override
String toString() {
return 'Task{id: $id, name: $title, age: $description}';
}
}
如果您不希望required
arguments ,则必须通过在其类型中添加问号来允许它们为null
,因此 Dart 将知道它们不需要初始化。 像这样:
int? id;
String? title;
String? description;
另一种解决方案是在构造函数中给它们一个默认值,但要小心为它们分配的值不会与代码的 rest 冲突:
Task({this.id=-1, this.title='Title' , this.description = 'Description'});
选择最适合您的方法:您还可以混合使用这两种解决方案,例如使某些属性可为空并为其他属性提供默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.