2

How to Solve Error: Non-nullable instance field 'id' must be initialized. Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.

class CategoryModel {
  int id;
  String name;

  CategoryModel({
    required this.id,
    required this.name,
  });

  CategoryModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
  }
  • you just need to add a null check operator or else a value to it so that it will not be null. ex. int? id; String? name; – Why_So_Ezz Dec 28 '22 at 01:43
  • Assign id and name in the initializer list https://dart.dev/guides/language/language-tour#initializer-list – mmcdon20 Dec 28 '22 at 02:42

1 Answers1

0
  1. If your field (id, name e.g.) CANNOT be null at anytime, add required keyword.
class CategoryModel {
  final int id;
  final String name;

  CategoryModel({
    required this.id,
    required this.name,
  });

  CategoryModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
  }
  1. If your field CAN be null, make it nullable by adding ? and it doesn't need to be required field.
class CategoryModel {
  final int? id;
  final String? name;

  CategoryModel({
    this.id,
    this.name,
  });

  CategoryModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
  }