来自斯威夫特,这在斯威夫特很好用-
class Test {
let userId: Int?
let id: Int?
let title: String?
init(userId: Int, id: Int, title: String) {
self.id = id
self.title = title
self.userId = userId
}
}
现在,在尝试dart文档时,我尝试了这个方法,它工作正常
class Album {
int? userId;
int? id;
String? title;
Album({required int userId, required int id, required String title}) {
this.userId = userId;
this.id = id;
this.title = title;
}
}
但如果我要添加最终关键字,这是像让在swift它停止工作,我必须做一些事情,如下面-
class Album {
final int? userId;
final int? id;
final String? title;
const Album({required this.id, required this.userId, required this.title});
}
我不知道为什么这个工作,为什么下面的不-这只是我必须开始做的事情,或者背后有任何逻辑以及-
class Album {
final int? userId;
final int? id;
final String? title;
Album({required int userId, required int id, required String title}) {
this.userId = userId;
this.id = id;
this.title = title;
}
}
2条答案
按热度按时间nfg76nw01#
你可以使用一个初始化器列表来初始化构造函数外部的final变量,如下所示:
但是对于这个例子,你真的应该把它写成
这样更符合习惯,更简洁。没有理由用另外一种方式来写。
voase2hg2#
Dart空安全。您可以使用
late
关键字。但是对于同名的更好的做法是
更多关于null-safety的信息。