首页 > 解决方案 > 在 Flutter(Dart) 中访问嵌套实例对象中的数据

问题描述

我比较陌生。我正在使用异步未来和未来构建来使用嵌套对象中的返回数据填充小部件。我遇到的问题是访问对象内的嵌套对象列表。[Instance of 'License', Instance of 'License', Instance of 'License', Instance of 'License', Instance of 'License']当我登录而不是 json? 时,我不断得到snapshot.data!.license ,当我尝试创建列表视图时,输出为空。我的观点是这样的:

body: SingleChildScrollView(
            child: new FutureBuilder<Profile>(
                future: _license,
                builder: (context, snapshot) {
                  if (snapshot.hasData == false || snapshot.data == null) {
                    return CircularProgressIndicator();
                  } else if (snapshot.hasError) {
                    return Text("${snapshot.error}");
                  } else {
                    var x = snapshot.data!.license;

                    x.map((e) {
                      print(e);
                      return Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(e.fromDate.toString()),
                                ])
                          ]);
                    });
                  }
                  return const Center(child: CircularProgressIndicator());
                })

        )

我的对象看起来像这样:

{
"id": "1",
"license": [
        {
            "license_no": "229451",
            "from_date": "2020-11-12",
            "to_date": "2021-11-30",
            "workStation": "Johpas Clinic"
        },
        {
            "license_no": "189024",
            "from_date": "2019-11-04",
            "to_date": "2020-11-30",
            "workStation": null
        },
        {
            "license_no": "109872",
            "from_date": "2016-11-30",
            "to_date": "2019-11-30",
            "workStation": null
        },
        {
            "license_no": "066356",
            "from_date": "2013-11-30",
            "to_date": "2016-11-30",
            "workStation": null
        },
        {
            "license_no": "007853    ",
            "from_date": "2010-11-30",
            "to_date": "2013-11-30",
            "workStation": null
        }
    ]
}

标签: flutterdart

解决方案


您可以在类中创建一个toJson方法,License然后将其用于日志记录目的,或者覆盖toString添加到 dart 中创建的每个类的方法。

class License {
String id;
License(this.id);

Map<String, dynamic> toJson() => {
 'id' : id,
};

推荐阅读