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
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.
2
Answers
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
This is the normal way we do this in Dart/Flutter:
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.