Home > front end >  Non-nullable instance field 'groupCreated' must be initialized
Non-nullable instance field 'groupCreated' must be initialized

Time:06-02

Non-nullable instance field 'groupCreated' must be initialized. Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.

class GroupModel {
  String id;
  String name;
  String leader;
  List<String> members;
  Timestamp groupCreated;

  GroupModel({
    required this.id,
    required this.name,
    required this.leader,
    required this.members,
    required this.groupCreated,
  });

  GroupModel.fromDocumentSnapshot({required DocumentSnapshot doc}) {
    id = doc.id;
    name = doc.get("name");
    leader = doc.get("leader");
    members = List<String>.from(doc.get("members"));
    groupCreated = doc.get("groupCreated");
  }
}

CodePudding user response:

You probably should use the constructor's initializer list for this:

GroupModel.fromDocumentSnapshot({required DocumentSnapshot doc})
    : id = doc.id,
      name = doc.get("name"),
      leader = doc.get("leader"),
      members = List<String>.from(doc.get("members")),
      groupCreated = doc.get("groupCreated");

When using a named constructor, the order is as follows:

  1. initializer list (after the :)
  2. superclass’s no-arg constructor
  3. main class’s no-arg constructor

Only after this, the body of a constructor is executed, more like an 'on init' callback. Here the object is expected to already be constructed completely. If you would have values that can only be initialized within that body, you can use late for that.

This is explained in detail in the docs on Dart's website, in the Constructors section

CodePudding user response:

You should use a constructor as described in the previous comment or use factory:

factory GroupModel.fromDocumentSnapshot({required DocumentSnapshot doc}) {
    return GroupModel(
      id: doc.id;
      name: doc.get("name");
      leader: doc.get("leader");
      members: List<String>.from(doc.get("members"));
      groupCreated: doc.get("groupCreated");
    );
  }
  • Related