In the code shown in the previous section, even if the objects contained in the JSON file miss pieces of data that are extremely important for our app (such as the name of the pizza or its ID), we still create an instance of the pizza. But this is not always required, nor recommended. That's why we can leverage the factory constructor, and only create a new instance of a Pizza when its id and pizzaName are valid. Follow these steps:
- Edit the PizzaList.json file so that the object with "id": 2 has no pizzaName:
{
"id": 2,
"description": 0,
"price": 7.50,
"imageUrl": "images/marinara.png"
},
- In the pizza.dart file, in the Pizza class, add a new factory constructor method:
Pizza();
factory Pizza.fromJsonOrNull(Map<String, dynamic> json) {
Pizza pizza = Pizza();
pizza.id = (json['id'] != null) ?
int.tryParse(json['id'].toString()) : 0;
pizza.pizzaName...