I am trying to fetch data from API and store the data in a list so that I can use the listin my code but it gives an error of Invalid value: Valid value range is empty: 0
Below is the code
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);
}
}
}
I want to use it in the below 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]);
},
),
Maybe your data is empty, try this:
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')
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.