KARTHIKEYAN N
KARTHIKEYAN N

Reputation: 81

How to loop objects inside of list in ListView.Builder

I am doing looping over the list items in ListView.builder

List _rBoxes = new List();//declare

the data i want to loop is seems like this:

{    
    "box_content": {
        "box_1": [
            {
                "id": "9",
                "name": "abc"
            },
            {
                "id": "10",
                "name": "xyz"
            }
        ],
        "box_2": [
            {
                "id": "8",
                "name": "acc"
            }
        ],
        "box_3": [
            {
                "id": "1",
                "name": "abc"
            }
        ],
        "box_4": [
            {
                "id": "4",
                "name": "amno"
            },
            {
                "id": "6",
                "name": "jkl"
            }
        ],
        "box_5": [
            {
                "id": "7",
                "name": "xre"
            }
        ]
    }    
}

then i add this items to the list

_rBoxes.addAll(data['box_content']);//it gives error - Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>'

//widget design

ListView.builder(
                        physics: NeverScrollableScrollPhysics(),
                        itemCount: _rBoxItems.length,
                        itemBuilder: (BuildContext context, int index) {
                          return Text("${_rBoxItems[index]}",
                              style: TextStyle(fontSize: 20.0));
                        })

Error : //here i want to loop box_1 index (only) in list view, how to acheive this if i gave _rBoxItems['box_1'].length the error will occur . actucally am stuck in this scenario, help me to resolve this problem.

Upvotes: 1

Views: 2052

Answers (3)

Onur
Onur

Reputation: 316

I think you want to iterate Box Context. If you fetch data from an API firstly you should create your data models and for that you can use app.quicktype.io it is working very well for dart. When I add your Box_1 content to there it gave to me a object like that. enter image description here

After creating your data models. You can use this function to get object from json string and you can convert them to a list. Box.fromJson(String str) => Box.fromMap(json.decode(str));

Upvotes: 1

hysunny
hysunny

Reputation: 111

because you're data['box_content'] is a Map, but _rBoxes.addAll needs a List, So it's going to report an error:

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>

you should convert data['box_content'] to List, like this:

_rBoxes.addAll(data['box_content'].entries.map((entry) => { entry.key, entry.value }).toList());

hope helpful ^_^

Upvotes: 0

Kavin-K
Kavin-K

Reputation: 2117

First you need to create Data model to parse your json data into a model, Data class should look like,

class Data {
  BoxContent boxContent;

  Data({this.boxContent});

  Data.fromJson(Map<String, dynamic> json) {
    boxContent = json['box_content'] != null
        ? new BoxContent.fromJson(json['box_content'])
        : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.boxContent != null) {
      data['box_content'] = this.boxContent.toJson();
    }
    return data;
  }
}

class BoxContent {
  List<Box> box;

  BoxContent({this.box});

  BoxContent.fromJson(Map<String, dynamic> json) {
    if (json['box'] != null) {
      box = new List<Box>();
      json['box'].forEach((v) {
        box.add(new Box.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.box != null) {
      data['box'] = this.box.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Box {
  String id;
  String name;

  Box({this.id, this.name});

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

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

Then parse json data into your Data model like,

import 'dart:convert';  // import this


String jsonData = "{ ... }" // your json as string

Data _data= Data.fromJson(jsonDecode(jsonData));

Finally you can achieve what you required,

ListView.builder(
    physics: NeverScrollableScrollPhysics(),
    itemCount: _rBoxItems.length,
    itemBuilder: (BuildContext context, int index) {
        return Text(_data.boxContent.box[index].length.toString(),
            style: TextStyle(fontSize: 20.0),
        );
}),

Note: You can simply generate models to parse, from json data here

Upvotes: 1

Related Questions