[英]"RangeError (index): Invalid value: Valid value range is empty: 2" with flutter carousel
[英]Flutter Invalid value: Valid value range is empty: 0
我正在嘗試從 API 獲取數據並將數據存儲在列表中,以便我可以在我的代碼中使用該列表,但它給出了無效值錯誤:有效值范圍為空:0
下面是代碼
class Services {
final String apiKey = '*Hidden*';
static const int numberOfFood = 50;
List<String> foodNameList = [];
getRandomBreakfast() async {
http.Response response = await http.get(
Uri.parse(
'https://api.spoonacular.com/recipes/random?apiKey=$apiKey&number=$numberOfFood&tags=breakfast?'),
);
dynamic foodData = response.body;
Map data = json.decode(foodData);
for (int i = 0; i < numberOfFood; i++) {
String foodName = (data['recipes'][i]['title']);
foodNameList.add(foodName);
}
}
}
我想在下面的 GridView builder 中使用它
GridView.builder(
itemCount: Services.numberOfFood,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 10,
childAspectRatio: 0.7,
),
itemBuilder: (context, index) {
return FoodContainer(
foodLabel: Services().foodNameList[index]);
},
),
也許你的數據是空的,試試這個:
for (int i = 0; i < numberOfFood; i++) {
if ((data['recipes'] as List).isNotEmpty) {
String foodName = (data['recipes'][i]['title']);
foodNameList.add(foodName);
} else {
print('Empty')
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.