0
class Product {


int id;
  String name;
  String description;
  double unitPrice;

  Product(this.id, this.name, this.description, this.unitPrice);
  Product.withId(this.id, this.name, this.description, this.unitPrice);

  Future<Map<String, dynamic>> toMap() async {
    var map = <String, dynamic>{};
    map["name"] = name;
    map["description"] = description;
    map["unitPrice"] = unitPrice;
    map["id"] = id;
  }

   Product.fromObject(dynamic o){
    id = int.tryParse(o["id"])!;
    name = o["name"];
    description = o["description"];
    unitPrice = double.tryParse(o["unitPrice"])!;
  }
}

Getting an error like this:

The body might complete normally, causing 'null' to be returned, but the return type, 'FutureOr<Map<String, dynamic>>', is a potentially non-nullable type.

Non-nullable instance field 'description' must be initialized.

Non-nullable instance field 'id' must be initialized.

Non-nullable instance field 'name' must be initialized.

Non-nullable instance field 'unitPrice' must be initialized.

  • In your `toMap` method you are forgetting to `return map;`, in your `Product.fromObject` constructor you should use the [initializer list](https://dart.dev/guides/language/language-tour#initializer-list) when initializing your properties. – mmcdon20 Feb 20 '23 at 02:49
  • [How do I initialize non-nullable members in a constructor body?](https://stackoverflow.com/q/66725613/) – jamesdlin Feb 20 '23 at 03:35

1 Answers1

0

You should return the map in toMap and initialize properties in the constructor.

class Product {

  int id;
  String name;
  String description;
  double unitPrice;

  Product(this.id, this.name, this.description, this.unitPrice);
  Product.withId(this.id, this.name, this.description, this.unitPrice);

  Future<Map<String, dynamic>> toMap() async {
    var map = <String, dynamic>{};
    map["name"] = name;
    map["description"] = description;
    map["unitPrice"] = unitPrice;
    map["id"] = id;
    return map;
  }

  Product.fromObject(dynamic o):
    id = int.tryParse(o["id"])!,
    name = o["name"],
    description = o["description"],
    unitPrice = double.tryParse(o["unitPrice"])!;
}
Alex Sunder Singh
  • 2,378
  • 1
  • 7
  • 17