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

标签 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()放到打印中,并返回正确的字符串(“ curry 饭和鹰嘴 bean ”)。打印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

    };
  }

}

请帮忙

最佳答案

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

关于loops - For循环在Dart中表现怪异。我试图做一个异步功能来检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62247089/

相关文章:

python - Python中的网格搜索功能

C - 函数仅在循环至少 17 次时才工作

java - 使用 Break Java Scanner 单独求和

android - 异常 : Unable to generate build files in flutter

firebase - 使用 Mockito 为 Firebase 用户身份验证设置单元测试

dart - 抖动动画 flutter

flutter - 启动到物理设备时出现空白屏幕

Java 程序陷入用户输入循环

flutter - 在 onTap ( Flutter ListItem ) 中执行函数后如何更改图标的颜色

ios - 如何在键盘外观上为 Flutter 布局设置动画