Flutter Dart-如何让类初始值设定项函数与构造函数一起工作?
如果通过构造函数创建实例,则忽略初始值设定项函数。如何使初始值设定项函数也在构造函数上工作? 这是我如何称呼这个班的Flutter Dart-如何让类初始值设定项函数与构造函数一起工作?,flutter,dart,Flutter,Dart,如果通过构造函数创建实例,则忽略初始值设定项函数。如何使初始值设定项函数也在构造函数上工作? 这是我如何称呼这个班的 User fireBaseUser = new User("12345","Test Name"); // shortenedName exists var snap = {"uid" : "12345", "displayName" : "Test Name"}; User fireBaseUser = User.fromSnapshot(snap); // shortened
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(' '));
}
相关的您使用了“命名参数{}”,因此应该使用参数名 1) 存在shortenedName 用户fireBaseUser=新用户(uid:“12345”,fireBaseDisplayName:“测试名称”,shortenedName:“TN”) 2) shortenedName不存在 用户fireBaseUser=新用户(uid:“12345”,fireBaseDisplayName:“测试名称”)
这是一个生成构造函数:
User(
{this.uid,
this.fireBaseDisplayName,
this.shortenedName,
}) {
shortenName(fireBaseDisplayName);
}
User.fromSnapshot( DocumentSnapshot document)
: uid = snapshot.documentID,
fireBaseDisplayName = snapshot['displayName'];
这是一个名为的构造函数:
User(
{this.uid,
this.fireBaseDisplayName,
this.shortenedName,
}) {
shortenName(fireBaseDisplayName);
}
User.fromSnapshot( DocumentSnapshot document)
: uid = snapshot.documentID,
fireBaseDisplayName = snapshot['displayName'];
在对象中初始化User fireBaseUser=User.fromSnapshot(snap)
您正在调用命名构造函数
,因此必须调用funshortenName(fireBaseDisplayName)
在您正在调用的命名构造函数中,如下所示:
User.fromSnapshot( DocumentSnapshot document)
: uid = snapshot.documentID, // snapshot or document? :)
fireBaseDisplayName = snapshot['displayName'] {
shortenName(fireBaseDisplayName);
}
见文件