有没有办法用函数初始化类的字段(需要多个步骤)?
示例:而不是:
class User {
final String uid;
final String fireBaseDisplayName;
String shortenedName;
User({
this.uid,
this.fireBaseDisplayName,
}) : shortenedName =
fireBaseDisplayName.substring(0, fireBaseDisplayName.indexOf(' '));
}
这可能吗:
User({
this.uid,
this.fireBaseDisplayName,
}) : shortenedName =
shortenName(this.fireBaseDisplayName));
}
shortenName (fireBaseDisplayName) {
return fireBaseDisplayName.substring(0, fireBaseDisplayName.indexOf(' ');
};
Related Dart 中的构造函数和初始化列表有什么区别? https://stackoverflow.com/questions/52013357/what-is-the-difference-between-constructor-and-initializer-list-in-dart
是的,您可以使用函数初始化字段,但有一个问题:它必须是static
。要么将函数声明为static
在你的课堂上或将其完全移到课堂外。如果该字段不是final
(对于最佳实践来说,应该是这样,除非该领域has变异),您可以在构造函数主体中使用常规非静态方法对其进行初始化。
最终字段必须使用静态函数初始化的原因是因为如果该函数不是静态的,它就可以访问this
。然而,this
在初始化所有最终字段之前不可用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)