1

It looks easy, but not working. I have model in Dart like this:

class FormTab {
  String caption;
  FormTab(dynamic m) { // where m will be Map
    this.caption = m['caption'] ?? "No caption";
  }
}

But still I have error message: Non-nullable instance field 'caption' must be initialized. Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'. What is wrong? I set value caption, but still I have error. I tried caption

sosnus
  • 968
  • 10
  • 28

1 Answers1

2

The body of a constructor in Dart is not part of the initializers. You need to put that into the initializer list:

class FormTab {
  String caption;
  FormTab(dynamic m) : caption = m['caption'] ?? "No caption";
}

Please note that if you know it's going to be a map, it might be better to make it a map. The earlier you switch from dynamic to actual types, the easier it is to catch errors.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • thank You! I just start write this class, and now I must add new, more advanced fields, so probably I must do it using `late` word, but thank You, Your response is very important for me – sosnus Jun 06 '22 at 10:36