Home > Software engineering >  Non-nullable instance field must be initialized (data persistence)
Non-nullable instance field must be initialized (data persistence)

Time:02-11

I want to correct the error of the code. My Problem is:

enter image description here

Non-nullable instance fields must be initialized.

CodePudding user response:

Non-nullable fields are supposed to get initialized during the object creation, which is even before the constructor body is executed. To do so use an initialization list like

Course(dynamic obj): _id = obj['id'], _name = obj['name'] {}

CodePudding user response:

This is the normal way we do this in Dart/Flutter:

    class Course {
      final int id;
      final String name;
      final String content;
      final int hours;
      
      const Course({
        this.id = 0;
        this.name = '';
        this.content = '';
        this.hours = 0;
      });
      
      factory Course.fromMap<String, dynamic> data) {
        return Course(
          id: data['id'] as int,
          name: data['name'] as String,
          content: data['content'] as String,
          hours: data['hours'] as int,
        );
      }
    }

    ...
    
    
    final course = Course.fromMap(data);
    

We don't usually use underscore (private) variables for data classes because Dart will automatically provide getters to access the fields via the dot notation.

final name = course.name;

CodePudding user response:

Try adding this. before like this:

Course(dynamic obj){
   this._id = obj['id];
}
  • Related