【问题标题】:How to loop objects inside of list in ListView.Builder如何在 ListView.Builder 中的列表内循环对象
【发布时间】:2021-03-04 12:17:24
【问题描述】:

我正在遍历 ListView.builder 中的列表项

List _rBoxes = new List();//declare

我要循环的数据是这样的:

{    
    "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"
            }
        ]
    }    
}

然后我将这些项目添加到列表中

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

//小部件设计

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

错误: //这里我想在列表视图中循环box_1索引(仅),如果我给了如何实现这个 _rBoxItems['box_1'].length 会发生错误。实际上我陷入了这种情况,请帮我解决这个问题。

【问题讨论】:

  • _rBoxes.addAll(data['box_content']); 你想全部添加到rBoxes 吗?

标签: flutter dart flutter-layout


【解决方案1】:

首先你需要创建Data模型来将你的json数据解析成一个模型,Data类应该是这样的,

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;
  }
}

然后将 json 数据解析到您的 Data 模型中,例如,

import 'dart:convert';  // import this


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

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

终于可以达到你的要求了,

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),
        );
}),

注意:您可以简单地从 json 数据 here 生成要解析的模型

【讨论】:

    【解决方案2】:

    因为你data['box_content']是一个Map,但是_rBoxes.addAll需要一个List,所以会报错:

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

    您应该将data['box_content'] 转换为列表,如下所示:

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

    希望对你有帮助^_^

    【讨论】:

    • 是的,它清除了错误,但我只想在列表视图构建器中循环 box_1 对象,目前它循环 box_content 内的完整对象。 @hysunny
    • ok~ 其实把Map转成List后很容易得到box_1,可以用List[0]。跨度>
    • 你的意思是: ListView.builder(itemCount: _rBoxItems[0].length,itemBuilder: (BuildContext context, int index) { return Text(_rBoxItems[0][index].toString()) ; })
    【解决方案3】:

    我认为您想迭代 Box Context。如果您首先从 API 获取数据,您应该创建您的数据模型,为此您可以使用 app.quicktype.io 它非常适合 dart。当我将您的 Box_1 内容添加到那里时,它给了我一个类似的对象。

    创建数据模型之后。您可以使用此函数从 json 字符串中获取对象,并将它们转换为列表。 Box.fromJson(String str) =&gt; Box.fromMap(json.decode(str));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-14
      相关资源
      最近更新 更多