gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:46:12 25 4
gpt4 key购买 nike

我试图做一个异步函数来从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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com