gpt4 book ai didi

flutter - Dart-如何让类初始化函数与构造函数一起使用?

转载 作者:行者123 更新时间:2023-12-03 04:45:32 24 4
gpt4 key购买 nike

如果我通过构造函数创建实例,则忽略初始化函数。如何使构造函数也能在构造函数上工作?
这是我叫课的方式

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?

最佳答案

这是一个generative constructor:

User(
{this.uid,
this.fireBaseDisplayName,
this.shortenedName,
}) {
shortenName(fireBaseDisplayName);
}

这是一个 named constructor:
User.fromSnapshot( DocumentSnapshot document)
: uid = snapshot.documentID,
fireBaseDisplayName = snapshot['displayName'];

在对象初始化 User fireBaseUser = User.fromSnapshot(snap);中,您正在调用 named constructor,因此您必须在正在调用的 shortenName(fireBaseDisplayName);中调用有趣的 named constructor,如下所示:
User.fromSnapshot( DocumentSnapshot document)
: uid = snapshot.documentID, // snapshot or document? :)
fireBaseDisplayName = snapshot['displayName'] {
shortenName(fireBaseDisplayName);
}

关于flutter - Dart-如何让类初始化函数与构造函数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62402637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com