Json Array Key not Present In Dart

Json Array Key not Present In Dart :

import 'dart:convert';

var jsonStr = """
{
  "id": 1,
  "firstName": "kamlesh",
  "lastName": "lakhani",
  "email": "",
  "vip": true,
  "shippingAddresses": [
    {
      "city": "Ahmedabad",
      "state": "Gujarat",
      "country": "India",
      "zipcode": "79105"
    },
    {
      "address": "Address",
      "city": "Apache Junction",
      "state": "Gujarat",
      "country": "India"
    }
  ],
  "dateOfBirth": "-"
}
""";

class User {
  int id;
  String firstName, lastName, email;
  bool vip;
  String dateOfBirth;
  List<dynamic> shippingAddresses;

  User({
    this.id,
    this.firstName,
    this.lastName,
    this.email,
    this.vip,
    this.dateOfBirth,
    this.shippingAddresses,
  });

  factory User.fromJson(Map<String, dynamic> json) {
    return new User(
        id: json['id'],
        firstName: json['firstName'],
        lastName: json['lastName'],
        email: json['email'],
        vip: json['vip'],
        dateOfBirth: json['dateOfBirth'],
        shippingAddresses: json['shippingAddresses']
            .map((value) => new Address.fromJson(value))
            .toList());
  }
}

class Address {
  String address, city, state, country, zipcode;

  Address({
    this.address,
    this.city,
    this.state,
    this.country,
    this.zipcode,
  });

  factory Address.fromJson(Map<String, dynamic> json) {
    return new Address(
        address: json['address'],
        city: json['city'],
        state: json['state'],
        country: json['country'],
        zipcode: json['zipcode']);
  }
}

void main() {
  var result = json.decode(jsonStr);
  var user = new User.fromJson(result);

  for (var data in user.shippingAddresses) {
    print(data.address == null ? 'Key not present': data.address);
  }
}

output :

Key not present
Address

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in