如何使用 dart 中的函数初始化类的字段?

gio*_*o79 5 dart flutter

有没有办法用函数初始化类的字段(需要多个步骤)?

示例:而不是:

class User {
  final String uid;
  final String fireBaseDisplayName;
  String shortenedName;

  User({
    this.uid,
    this.fireBaseDisplayName,
  }) : shortenedName =
            fireBaseDisplayName.substring(0, fireBaseDisplayName.indexOf(' '));
}
Run Code Online (Sandbox Code Playgroud)

这可能吗:

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

shortenName (fireBaseDisplayName) {
return fireBaseDisplayName.substring(0, fireBaseDisplayName.indexOf(' ');
};
Run Code Online (Sandbox Code Playgroud)

相关Dart 中的构造函数和初始化列表有什么区别?

Gre*_*rad 4

是的,您可以使用函数初始化字段,但有一个问题:它必须是static. 要么在类中声明该函数static,要么将其完全移到类之外。如果该字段不是final(为了最佳实践,它应该是,除非该字段必须发生变化),您可以在构造函数主体中使用常规非静态方法对其进行初始化。

必须使用静态函数初始化 Final 字段的原因是,如果该函数不是静态的,它就可以访问this. 但是,this直到所有最终字段都已初始化后才可用。