Функции инициализатора игнорируются, если я создаю экземпляр через конструктор. Как заставить функции инициализатора работать и с конструкторами? Вот как я вызываю класс
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(' '));
}
Связанные Как инициализировать поля класса с помощью функция в дротике?