Maxim Vershinin
Maxim Vershinin

Reputation: 643

How in Dart, instantiate an object with default modifiable list field

I have this class User and would like to be able to instantiate it with default modifiable field phoneNumbers as empty list, not as null or unmodifiable list.
I know that you can pass const [] to constructor but this list will be unmodifiable.

class User {
  String name;
  var phoneNumbers;

  UserData(
      {this.name = '',
      this.phoneNumbers});
}

Upvotes: 0

Views: 605

Answers (1)

Rémi Rousselet
Rémi Rousselet

Reputation: 276957

You can either initialize the field directly:

class User {
  String name;
  var phoneNumbers = [];

  UserData(
      {this.name = '',
      this.phoneNumbers});
}

or use constructor initializers:

class User {
  String name;
  var phoneNumbers;

  UserData(
      {this.name = '',
      this.phoneNumbers}): phoneNumbers = phoneNumbers ?? [];
}

Upvotes: 1

Related Questions