【发布时间】:2020-10-05 17:10:57
【问题描述】:
如果我通过构造函数创建实例,初始化函数将被忽略。如何让初始化函数也适用于构造函数? 这是我如何称呼班级
User fireBaseUser = new User("12345","Test Name"); // shortenedName exists
var snap = {"uid" : "12345", "displayName" : "Test Name"};
User fireBaseUser = User.fromSnapshot(snap); // shortenedName wont exist
class User {
final String uid;
final String fireBaseDisplayName;
String shortenedName;
User.fromSnapshot( DocumentSnapshot document)
: uid = snapshot.documentID,
fireBaseDisplayName = snapshot['displayName'];
User(
{this.uid,
this.fireBaseDisplayName,
this.shortenedName,
}) {
shortenName(fireBaseDisplayName);
}
shortenName(fireBaseDisplayName) {
shortenedName =
fireBaseDisplayName.substring(0, fireBaseDisplayName.indexOf(' '));
}
只有当我像这样复制初始化函数时,构造函数似乎才能工作
class User {
final String uid;
final String fireBaseDisplayName;
String shortenedName;
User.fromSnapshot( DocumentSnapshot document)
: uid = snapshot.documentID,
fireBaseDisplayName = snapshot['displayName'];
shortenedName = snapshot['displayName'].substring(0, snapshot['displayName'].indexOf(' '));
User(
{this.uid,
this.fireBaseDisplayName,
this.shortenedName,
}) {
shortenName(fireBaseDisplayName);
}
shortenName(fireBaseDisplayName) {
shortenedName =
fireBaseDisplayName.substring(0, fireBaseDisplayName.indexOf(' '));
}
相关How to initialize a class' fields with a function in dart?
【问题讨论】: