How to initialize a class' fields with a function in dart?

Viewed 3224

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

Example: instead of:

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

  User({
    this.uid,
    this.fireBaseDisplayName,
  }) : shortenedName =
            fireBaseDisplayName.substring(0, fireBaseDisplayName.indexOf(' '));
}

would this be possible:

  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?

2 Answers

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.

Is this what you want?

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);
  }
}
Related