问题描述
我正在尝试将复杂的 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 错误。
解决方法
@fartem 几乎回答正确,除非您需要按索引动态访问您的项目(不仅仅是第一个项目)。在您在 itemBuilder
中使用函数 ListView.builder
的代码行中,而不是
itemBuilder: (BuildContext context,snapshot) {
我建议使用
itemBuilder: (BuildContext context,i) {
因为第二个参数是一个索引。因此,为了能够获得列表中每个项目的名称,您必须使用该索引:
title: Text('${driver.data.routes[i].name}'),
等等。
,Routes 是一个数组,你可以尝试通过 driver.data.routes[0].name