For循环在Dart中表现异常。我试图做一个异步功能来检索数据

时间:2020-06-07 14:50:33

标签: loops flutter dart async-await

我试图做一个异步函数来从API获取数据,并在Flutter的FutureBuilder中使用它。但是函数内部的for循环表现得非常奇怪。它仅执行for循环标题下方的语句。

Future<List<Dish>> getData() async {

List<Dish> cuisineDishes;

Response response = await get('https://api.spoonacular.com/recipes/search?apiKey=$apiKey&cuisine=$cuisineType&number=$number');
Map data = jsonDecode(response.body);

for (int i=0; i<number; i++)
{ print('111');
  cuisineDishes[i].dishName = data['results'][i]['title'].toString();  
  String dishID = data['results'][i]['id'].toString(); 
  print('222');

  Response response2 = await get('https://api.spoonacular.com/recipes/$dishID/ingredientWidget.json?apiKey=$apiKey');
  Map ingredientsData = jsonDecode(response2.body);

  String ingredientsString;
  List<String> ingredients;

  for (int j =0; j<ingredientsData['ingredients'].toList().length; j++)
  {
    ingredientsString += '${ingredientsData['ingredients'][j]['name']} ';
  }

  ingredients = ingredientsString.split(' ');
  cuisineDishes[i].ingredients = ingredients;
  cuisineDishes[i].dishType = ' ';
  cuisineDishes[i].special = 0;

}

return cuisineDishes;

}

在这种情况下,仅打印111。 API请求没有任何问题,我尝试将data['results'][i]['title'].toString()打印出来,并返回了正确的字符串(“鹰嘴豆咖喱饭”)。打印data['results'][i]['id']还会打印一个有效的ID。

这是菜式:-

class Dish
{
  String dishType;
  String dishName;
  List<String> ingredients;
  int special;

  Dish([this.dishType, this.dishName, this.ingredients, this.special=0]);


  Map<String, dynamic> toMap() {

    String ingredientsText = ingredients[0];
    for (int i=1; i<ingredients.length; i++)
    ingredientsText += " ${ingredients[i]}";

    return {

      'dishType': dishType,
      'dishName' : dishName,
      'ingredients' : ingredientsText,
      'special' : special

    };
  }

}

请帮助

2 个答案:

答案 0 :(得分:1)

您可能需要在响应后添加到地图。同样,data ['results]]必须提供一个List>,在到达其嵌套之前,您还需要对其进行强制转换。

答案 1 :(得分:0)

这是一个简单的错误 List<Dish> cuisineDishes;应该是 List<Dish> cuisineDishes = new List();,因为它是可增长的列表。