Home > Software engineering >  Dart initializer in constructor
Dart initializer in constructor

Time:06-06

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

CodePudding user response:

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.

CodePudding user response:

And you may try with late keyword as well as

main(){
  print(FormTab({"caption":"test"}).caption);
}
class FormTab {
  late String caption;
  FormTab(Map m) {// with map
    caption = m['caption'] ?? "No caption";
  } 
}

output: test

  • Related