Non-nullable instance field 'buttonStartingYpoint' must be initialized

Issue

This is My model class. I am trying to get an http response and print it to my app.

At line 12 DataModel it’s showing me this error

"Non-nullable instance field ‘buttonStartingYpoint’ must be initialized.
Try adding an initializer expression, or add a field initializer in this constructor, or mark it ‘late’."

Non-nullable instance field ‘buttonHeight’ must be initialized.
Try adding an initializer expression, or add a field initializer in this constructor, or mark it ‘late’

  String buttonLetter;
  int buttonHeight;
  int buttonWidth;
  int buttonStartingXpoint;
  int buttonStartingYpoint;

  DataModel(
      {required this.buttonLetter,
      required this.buttonHeight,
      required this.buttonWidth,
      required this.buttonStartingXpoint,
      required this.buttonStartingYpoint});

  DataModel.fromJson(Map<String, dynamic> json) {
    buttonLetter = json['Button_letter'];
    buttonHeight = json['Button_height'];
    buttonWidth = json['Button_width'];
    buttonStartingXpoint = json['Button_Starting_xpoint'];
    buttonStartingYpoint = json['Button_Starting_ypoint'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['Button_letter'] = this.buttonLetter;
    data['Button_height'] = this.buttonHeight;
    data['Button_width'] = this.buttonWidth;
    data['Button_Starting_xpoint'] = this.buttonStartingXpoint;
    data['Button_Starting_ypoint'] = this.buttonStartingYpoint;
    return data;
  }
}

I tried to add late but then its showing error in both late and model. And I am new to flutter

Solution

You have to initialize them in the initializer list. When you get to the constructor body it’s too late. Here’s the fix:

  DataModel.fromJson(Map<String, dynamic> json) :
    buttonLetter: json['Button_letter'],
    buttonHeight: json['Button_height'],
    buttonWidth: json['Button_width'],
    buttonStartingXpoint: json['Button_Starting_xpoint'],
    buttonStartingYpoint: json['Button_Starting_ypoint'];

For reference: https://dart.dev/guides/language/language-tour#constructors

Answered By – Gazihan Alankus

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *