Sayed  Ali
Sayed Ali

Reputation: 15

Non-nullable instance field must be initialized (data persistence)

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

enter image description here

Non-nullable instance fields must be initialized.

Upvotes: 0

Views: 213

Answers (2)

Roslan Amir
Roslan Amir

Reputation: 1336

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;

Upvotes: 1

hfxbse
hfxbse

Reputation: 36

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'] {}

Upvotes: 0

Related Questions