flutter - 在扩展图 block 中循环json

标签 flutter dart

我在尝试在小部件内循环json对象时遇到了大麻烦

我从api调用获取此json:

[
 {
  "id":21,
  "name":"John Smit",
  "date_birth":"30-09-1983",
  "cars":[
           {
            "id":406,
            "car_name":"Ford"
           }
          ]
 }
]


还有一个获得此数据的模型:
class Tiro {

  final int id;
  final String name;
  final String date_birth;
  final List cars;



  Tiro.fromJSON(Map<String, dynamic> jsonMap) :

    id= jsonMap['id'],
    name= jsonMap['name'],
    date_birth= jsonMap['date_birth'],
    cars= jsonMap['cars'];

}


现在,我将显示一个ExtensionTile,其文本类似于字符串名称,并且在他的 child 中有一些ListTile产生的循环进入List汽车:
class TiroTile extends StatelessWidget {
  final Tiro _tiro;


  TiroTile(this._tiro);

  @override

  Widget build(BuildContext context) {
    return Center(
      child: Card(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            ExpansionTile(
              title: Text(_tiro.name),
              leading: Icon(Icons.library_books,
              color: Colors.red[900],
              ),
              children: <Widget>[
                var myCars = jsonDecode(_tiro.cars);
                for (var s in myCars){
                  // here my ListTile
                }
              ],
            ),
          ],
        ),
      ),
    );
  }
}

当然这是行不通的,但是我不知道如何实现。
谢谢你的帮助。

最佳答案

您需要创建一个Car类,就像包含Tiro构造函数的fromJson类一样。问题是jsonMap['cars']返回List<dynamic>。我们需要将其转换为List类型,然后需要序列化此列表中的每个元素。因此,您需要包括以下更改-

var list = jsonMap['cars'] as List;

在构造函数中,您将执行以下操作-
cars: list.map((i) => Car.fromJson(i)).toList()

最后,看起来像这样-
factory Tiro.fromJSON(Map<String, dynamic> jsonMap){ // The way i have created the constructor is different, but it's upto you

    var list = jsonMap['cars'] as List;

    return Tiro(
      id : jsonMap['id'],
      name : jsonMap['name'],
      date_birth : jsonMap['date_birth'],
      cars: list.map((i) => Car.fromJson(i)).toList()
    );
  }

还要删除您创建的myCars变量,在完成上述更改后,您无需解码json。您可以使用_tiro.cars直接访问列表。

附加-

现在,如果您的Json是对象列表(如您的示例所示),则需要应用类似的逻辑。创建另一个具有字段TiroList的类List<Tiro> tiros,并执行上述相同的操作以序列化每个singe Tiro。

关于flutter - 在扩展图 block 中循环json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58099489/

相关文章:

flutter - 'RenderObject' 类型的值不能分配给 'RenderBox' 类型的变量

android - Flutter Android SDK 版本 28 错误,但我使用的是 30

flutter - Flutter 中带有文本和单选按钮的动态 ListView

flutter - 点击时如何更改容器的背景颜色

flutter - StreamBuilder 未按预期从 Stream 读取数据

flutter - 如何在 flutter 中将图像子对象放入容器内

google-maps - Flutter map_view 中心到用户位置

android - Flutter Webview 抛出编译错误-ThreadedInputConnectionProxyAdapterView location : class InputAwareWebView

dart - Dart 2.0是否具有扩展方法?

flutter - 由于堆叠屏幕 flutter ,Snackbar 显示两次,我该如何避免?