3

I'm using json_model plugin for making PODO class. I've successfully parsed the main array. But I can't put the images key that contains array of map in PODO class using that plugin and can't parse the data.

Here is the array that I want to parse below:

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    },
    "images": [
      {
        "id": 11,
        "imageName": "xCh-rhy"
      },
      {
        "id": 31,
        "imageName": "fjs-eun"
      },
      {
        "id": 51,
        "imageName": "asd-fdg"
      },
      {
        "id": 71,
        "imageName": "zxc-cvb"
      },
      {
        "id": 91,
        "imageName": "qwe-hgj"
      }
    ]
  },
    ...
]

Parsing JSON data here:

Future<List<Users>> _fetchUser() async {
  final response = await DefaultAssetBundle.of(context).loadString('users.json');
  if (response != null) {
    List users = json.decode(response.toString());
    return users.map((user) => Users.fromJson(user)).toList();
  } else {
    throw Exception('Failed to load data!');
  }
}

Trying to show data from images key:

FutureBuilder<List<Users>>(
  future: _fetchUser(),
  builder: (context, snapshot) {
    if (snapshot.hasError) {
      return Center(child: Text('Error: ${snapshot.error}'));
    } else if (snapshot.hasData) {
      List<Users> users = snapshot.data;
      return ListView.separated(
        separatorBuilder: (_, __) => const Divider(),
        itemCount: users.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text('${users[index].username}'),
            subtitle: Text('${users[index].images[index].imageName}'),
            onTap: () {
              Navigator.pushNamed(
                context,
                DetailsScreen.route,
                arguments: users[index],
              );
            },
          );
        },
      );
    } else {
      return const Center(child: CircularProgressIndicator());
    }
  },
),

But it's showing the error:

Index out of range: index should be less than 5:5

2 Answers 2

3

This is simple object with it, i don't consider your array. it only inner object model. You can generate model by this : https://javiercbk.github.io/json_to_dart/

    class Autogenerated {
    int id;
    String name;
    String username;
    String email;
    Address address;
    String phone;
    String website;
    Company company;
    List<Images> images;

    Autogenerated(
        {this.id,
        this.name,
        this.username,
        this.email,
        this.address,
        this.phone,
        this.website,
        this.company,
        this.images});

    Autogenerated.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        name = json['name'];
        username = json['username'];
        email = json['email'];
        address =
            json['address'] != null ? new Address.fromJson(json['address']) : null;
        phone = json['phone'];
        website = json['website'];
        company =
            json['company'] != null ? new Company.fromJson(json['company']) : null;
        if (json['images'] != null) {
        images = new List<Images>();
        json['images'].forEach((v) {
            images.add(new Images.fromJson(v));
        });
        }
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['id'] = this.id;
        data['name'] = this.name;
        data['username'] = this.username;
        data['email'] = this.email;
        if (this.address != null) {
        data['address'] = this.address.toJson();
        }
        data['phone'] = this.phone;
        data['website'] = this.website;
        if (this.company != null) {
        data['company'] = this.company.toJson();
        }
        if (this.images != null) {
        data['images'] = this.images.map((v) => v.toJson()).toList();
        }
        return data;
    }
    }

    class Address {
    String street;
    String suite;
    String city;
    String zipcode;
    Geo geo;

    Address({this.street, this.suite, this.city, this.zipcode, this.geo});

    Address.fromJson(Map<String, dynamic> json) {
        street = json['street'];
        suite = json['suite'];
        city = json['city'];
        zipcode = json['zipcode'];
        geo = json['geo'] != null ? new Geo.fromJson(json['geo']) : null;
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['street'] = this.street;
        data['suite'] = this.suite;
        data['city'] = this.city;
        data['zipcode'] = this.zipcode;
        if (this.geo != null) {
        data['geo'] = this.geo.toJson();
        }
        return data;
    }
    }

    class Geo {
    String lat;
    String lng;

    Geo({this.lat, this.lng});

    Geo.fromJson(Map<String, dynamic> json) {
        lat = json['lat'];
        lng = json['lng'];
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['lat'] = this.lat;
        data['lng'] = this.lng;
        return data;
    }
    }

    class Company {
    String name;
    String catchPhrase;
    String bs;

    Company({this.name, this.catchPhrase, this.bs});

    Company.fromJson(Map<String, dynamic> json) {
        name = json['name'];
        catchPhrase = json['catchPhrase'];
        bs = json['bs'];
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['name'] = this.name;
        data['catchPhrase'] = this.catchPhrase;
        data['bs'] = this.bs;
        return data;
    }
    }

    class Images {
    int id;
    String imageName;

    Images({this.id, this.imageName});

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

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['id'] = this.id;
        data['imageName'] = this.imageName;
        return data;
    }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much brother! You guided me to the more easiest way to parse the json. Can you please guide me that how can I show "images" array in flutter. BTW I'm using FutureBuilder.
Man, I'm coming from a javascript background and was doing this flutter project as a hobby. I had almost quit after I saw how they decode it. you deserve a freaking medal for that showing me that GitHub repository. Lots of love!
1

The suggested answer is OK, but some errors appear (even in the automatic converter, provided in the link). E.g.,

not OK:

Geo.fromJson(Map<String, dynamic> json) {
    lat = json['lat'];
    lng = json['lng'];
}

OK:

Geo.fromJson(Map<String, dynamic> json):
    lat = json['lat'],
    lng = json['lng'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.