如何使用Dart中的函数初始化类的字段? [英] How to initialize a class' fields with a function in dart?

查看:478
本文介绍了如何使用Dart中的函数初始化类的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用函数来初始化类的字段(需要多个步骤)?

Is there a way to initialize a field of a class with a function (where multiple steps would be required)?

示例:而不是:

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 What is the difference between constructor and initializer list in Dart?

推荐答案

是的,您可以使用函数初始化字段,但要注意的是:它必须是 static 。要么将函数声明为 static 或将其完全移到班外。如果该字段不是 final (最佳做法是,除非字段进行更改),则可以在构造函数主体中使用常规的非静态方法对其进行初始化。

Yes, you can initialize fields with a function, but here's the catch: it has to be static. Either declare the function as static in your class or move it outside the class altogether. If the field isn't final (which for best practice, it should be, unless the field has to mutate), you can initialize it using a regular non-static method in the constructor body.

最终字段必须使用静态函数进行初始化是因为如果该函数不是静态的,则可以访问。但是,在初始化所有最终字段之前,不可用。

The reason final fields have to be initialized using a static function is because if the function was not static, it would have access to this. However, this is not available until all final fields have been initialized.

这篇关于如何使用Dart中的函数初始化类的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆