我正在尝试从 API 获取列表。它显示错误-
RangeError (index): Invalid value: Only valid value is 0: 2
我正在练习fetch api。你能告诉我我的代码有什么问题以及如何避免在我的应用程序中显示红屏错误吗?
这是代码-
RefreshIndicator(
onRefresh: () {
setState(() {});
return fetchOpenMenuList(widget.product);
},
child: FutureBuilder<MenuListData>(
future: futureOpenMenuList,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
padding: EdgeInsets.symmetric(vertical: 8.h),
itemCount: snapshot.data!.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: Image.network(
snapshot.data!.data[index]!.items[index].thumb.toString()
),
title: Text(snapshot.data!.data[index]!.items[index].prodName),
subtitle: Text(snapshot.data!.data[index]!.name),
trailing: Container(
padding: EdgeInsets.all(5.r),
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.circular(10.r),
),
child: Image.asset("assets/images/MenuIcon.png", height: 20.h, width: 20.w)
),
);
},
);
} else if (snapshot.hasError) {
return Center(child: Text('No Data Found'));
}
return const Center(
child: SizedBox(
height: 50.0,
width: 50.0,
child: CircularProgressIndicator(),
),
);
},
),
),
这是我的JSON文件-
{
"ignore": 0,
"code": 1,
"message": "OK",
"data": [
{
"ctg_id": "1",
"name": "Fusion",
"items": [
{
"prod_id": "1",
"prod_name": "Italian Sev Puri",
"thumb": "http:\/\/www.galacaterers.in\/images\/menu-items\/thumb-1459925145.jpg"
}
]
},
{
"ctg_id": "5",
"name": "Cake And Pastries",
"items": [
{
"prod_id": "57",
"prod_name": "Molt And Magic",
"thumb": "http:\/\/www.galacaterers.in\/images\/menu-items\/thumb-1459945416.jpg"
},
{
"prod_id": "49",
"prod_name": "Chocolate Zuzups",
"thumb": "http:\/\/www.galacaterers.in\/images\/menu-items\/thumb-1459945068.jpg"
}
]
},
{
"ctg_id": "6",
"name": "Chaat",
"items": [
{
"prod_id": "99",
"prod_name": "Makai Roll Chaat",
"thumb": "http:\/\/www.galacaterers.in\/images\/menu-items\/thumb-1459966275.jpg"
}
]
},
{
"ctg_id": "46",
"name": "Sweet Bite",
"items": [
{
"prod_id": "23",
"prod_name": "Fruit Wati",
"thumb": "http:\/\/www.galacaterers.in\/images\/menu-items\/thumb-1459942869.jpg"
}
]
}
]
}
以下是报错截图:
您也在使用
index
进行 items
的迭代,这很糟糕。取而代之的是从items
.中获取第一个元素
你的
ListTile
代码应该像..
return ListTile(
leading: Image.network(
snapshot.data!.data[index]!.items[0].thumb.toString()//Make sure items is not empty
),
title: Text(snapshot.data!.data[index]!.items[0].prodName),
subtitle: Text(snapshot.data!.data[index]!.name),
trailing: Container(
padding: EdgeInsets.all(5.r),
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.circular(10.r),
),
child: Image.asset("assets/images/MenuIcon.png", height: 20.h, width: 20.w)
),
);