【问题标题】:How to initialize a class' fields with a function in dart?如何使用飞镖中的函数初始化类的字段?
【发布时间】:2020-06-15 17:24:44
【问题描述】:

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

示例:代替:

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(' ');
};

相关What is the difference between constructor and initializer list in Dart?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

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

    必须使用静态函数初始化最终字段的原因是,如果该函数不是静态的,它将可以访问this。但是,在所有最终字段都初始化之前,this 不可用。

    【讨论】:

    • 如果你使用具有 null 安全性的 Dart >= 2.12,String shortenedName; 字段会给你一个错误,因为它被标记为非 null 字段(因为它没有 ?) ,并且您需要添加late 关键字以避免编译器Non-nullable instance field 'shortenedName' must be initialized 错误;像这样:late String shortenedName;
    【解决方案2】:

    这是你想要的吗?

    void main() {
      var user = User(id: "0", name: "Test user");
      print(user.name);
      print(user.firstName);
      print(user.lastName);
    }
    
    class User {
      final String id;
      final String name;
      String firstName, lastName;
    
      User({
        this.id,
        this.name,
      }) {
        initFirstName();
        initLastName();
      }
    
      initFirstName() {
        firstName = name.substring(0, name.indexOf(' '));
      }
    
      initLastName() {
        lastName = name.substring(name.indexOf(' ') + 1);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-07
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 2011-03-16
      • 2023-03-04
      相关资源
      最近更新 更多