0

I have dart class made to interact with sqlite database:

class Note {
   int? id;
   String title;
   String content;
   DateTime date;
   bool important;
   

  Note({
    required this.title,
    required this.content,
    required this.date,
    this.important = false,
    
  });

After I added the named constructor an errors occurs:

"Non-nullable instance field 'content' must be initialized. Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'." for all fildes beside id.

  Note.fromMap(Map<String, dynamic> map) {
    id = map["id"];
    title = map["title"];
    content = map["content"];
    date = DateTime.parse(map["date"]);
    important = map["important"] == 1;
  }

Is adding a late to all fields is proper solution? And why is that? Code wokrs fine without named constructor and named constructor initialize all vars so why the error?

class Note {
  int? id;
  late String title;
  late String content;
  late DateTime date;
  late bool important;
...
ext0101
  • 1
  • 1

1 Answers1

0

Your fromMap method did not return a Note object, it just fills your actual object with the map data.

You can create a factory fromMap with this code:

class Note {

  ...

  factory Note.fromMap(Map<String, dynamic> map) => Note(
    title: map["title"],
    content: map["content"],
    date: DateTime.parse(map["date"]),
    important: map["important"] == 1,
  );

}
final note = Note.fromMap(sqliteMapData);

after that you can remove your late.

This is the official documentation for late: variable in Dart https://dart.dev/null-safety/understanding-null-safety#late-variables

late variable is not bad or good solution, you can have a good use cases (for example with the lazy initialization) but you can also have a runtime error if misused.

ArthurRmd
  • 156
  • 4