phillercode
phillercode

Reputation: 339

Is there a reason my enum is becoming null in a class constructor?

I am including an enum in a User class constructor. That field in the class becomes null in the new instance.

I directly set the enum value. I print the class field afterward. It is null.

enum Genders {
  MALE,
  FEMALE,
  OTHER
}

class User extends SharedUser {
  User(
      String firstName,
      Genders gender,
  ) : super (firstName: firstName);

  Genders gender;
}

final User user = User(
    'Bob',
    Genders.OTHER
);
print(user.firstName); // Bob
print(user.gender); // null

Expected: user.gender would print as Genders.OTHER

Actual: user.gender prints as null

Upvotes: 1

Views: 1450

Answers (1)

Rémi Rousselet
Rémi Rousselet

Reputation: 277057

Dart doesn't magically assign parameters constructor to the class fields. You have to specify such behavior yourself.

As such, your User constructor should become:

User(String firstName, this.gender): super(firstName: firstName);

Upvotes: 2

Related Questions