简体   繁体   English

Flutter 无效值:有效值范围为空:0

[英]Flutter Invalid value: Valid value range is empty: 0

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我正在尝试从 API 获取数据并将数据存储在列表中,以便我可以在我的代码中使用该列表,但它给出了无效值错误:有效值范围为空: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 中使用它

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')
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM