2

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

我的代码:

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 错误。

4

2 回答 2

1

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

itemBuilder: (BuildContext context, snapshot) {

我建议使用

itemBuilder: (BuildContext context, i) {

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

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

等等。

于 2021-01-30T20:14:23.953 回答
0

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

于 2021-01-30T19:59:12.490 回答