In this recipe, we will use constants instead of typing in the keys of each field of the JSON data. The starting code is at the end of the previous recipe:
- At the top of the pizza.dart file, add the constants that we will need later within the Pizza class:
const keyId = 'id';
const keyName = 'pizzaName';
const keyDescription = 'description';
const keyPrice = 'price';
const keyImage = 'imageUrl';
- In the Pizza.fromJson constructor, remove the strings for the JSON object and add the constants instead:
Pizza.fromJson(Map<String, dynamic> json) {
this.id = (json[keyId] != null) ? int.tryParse(json['id'].toString()) : 0;
this.pizzaName =
(json[keyName] != null) ? json[keyName].toString() : '';
this.description = (json[keyDescription] != null) ? json[keyDescription].toString() : '';
this.price = (json[keyPrice] != null && double.tryParse(json[keyPrice].toString()) != null) ? json[keyPrice...