skip to Main Content

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

enter image description here

Non-nullable instance fields must be initialized.

2

Answers


  1. 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'] {}
    
    Login or Signup to reply.
  2. 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 ?? 0,
              name: data['name'] as String ?? '',
              content: data['content'] as String ?? '',
              hours: data['hours'] as int ?? 0,
            );
          }
        }
    
        ...
        
        
        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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search