【问题标题】:Flutter Complex Parsing Json Undefined getter "List<Type>'Flutter 复杂解析 Json 未定义 getter “List<Type>”
【发布时间】:2021-01-30 19:44:44
【问题描述】:

我正在尝试将复杂的 json 文件解析到我的应用程序中,但出现错误:没有为类型“列表”定义 getter“名称”。我无法在我的路线列表中获取路线名称,但可以获取其他所有内容。 我不明白这是发生在哪里以及如何解决它。

我的代码:

void openBottomSheet() {
showModalBottomSheet(
    context: context,
    builder: (context) {
      return FutureBuilder<DriverDataModel>(
        future: mongoApi.getMongoData(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final driver = snapshot.data;
            return Container(
              child: ListView.builder(
                itemCount: driver.data.routes.length,
                itemBuilder: (BuildContext context, snapshot) {
                  return ListTile(
                    title: Text('${driver.data.routes.name}'),
                    leading: Icon(Icons.directions),
                    onTap: () {
                      drawPolyLine.cleanPolyline();
                      getCurrentLocation();
                      routesCoordinates.isInCourse(driver.data.routes);
                      Navigator.pop(context);
                    },
                  );
                },
              ),                
            );
          }
          return Container();
        },
      );
    });

Json 响应:

{

"success": true,
"data": {
    "_id": "600773ac1bde5d10e89511d1",
    "name": "Joselito",
    "truck": "5f640232ab8f032d18ce0137",
    "phone": "*************",
    "routes": [
        {
            "name": "Tere city",
            "week": [
                {
                    "short_name": "mon"
                }
            ],
            "coordinates": [
                {
                    "lat": -22.446938,
                    "lng": -42.982084
                },
                {
                    "lat": -22.434384,
                    "lng": -42.978511
                }
            ]
        }
    ],
    "createdAt": "2021-01-20T00:05:00.717Z",
    "updatedAt": "2021-01-20T00:05:00.717Z",
    "__v": 0
}

我使用https://app.quicktype.io/ 创建我的模型并成功解析。但是,当我尝试在路线列表中打印路线名称时,会出现 getter 错误。

【问题讨论】:

    标签: flutter jsonparser


    【解决方案1】:

    @fartem 几乎回答正确,只是您需要按索引动态访问您的项目(不仅仅是第一项)。在您的代码中,您在ListView.builder 中使用函数itemBuilder,而不是

    itemBuilder: (BuildContext context, snapshot) {

    我建议使用

    itemBuilder: (BuildContext context, i) {

    因为第二个参数是一个索引。因此,为了能够获取列表中每个项目的名称,您必须使用该索引:

    title: Text('${driver.data.routes[i].name}'),

    等等。

    【讨论】:

      【解决方案2】:

      Routes是一个数组,你可以尝试通过driver.data.routes[0].name调用它

      【讨论】:

        猜你喜欢
        • 2021-07-20
        • 2020-10-29
        • 2021-06-20
        • 2020-04-13
        • 2020-12-21
        • 2020-10-21
        • 1970-01-01
        相关资源
        最近更新 更多