尝试使用Spoonacular API构建配方应用。尝试使用Google搜索来寻找答案,但似乎uri.https格式有所变化,所有搜索结果均来自去年或更早的版本。我找不到正确的格式吗?这是我第一次在 flutter 朔迷离中调用API,我似乎无法正确地做到这一点。
这是教程:https://youtu.be/l3CIMZSAaIk
这是源代码:https://github.com/MarcusNg/flutter_recipe_app
此链接显示了如何生成膳食计划:
https://spoonacular.com/food-api/docs#Generate-Meal-Plan
这是我尝试以URL形式调用的方式:
https://api.spoonacular.com/mealplanner/generate?apiKey=[CHANGE_THIS_TO_APIKEY]&timeFrame=day&1700&vegan
这在浏览器中完美运行,我需要将其转换为 flutter 代码:
class APIservice {
APIservice._instantiate();
static final APIservice instance = APIservice._instantiate();
final String _baseUrl = 'api.spoonacular.com';
static const String API_KEY = '[APIKEY HERE]';
//Generate Meal Plan
Future<MealPlan> generateMealPlan({int targetCalories, String diet}) async {
if (diet == 'None') diet = '';
Map<String, String> parameters = {
'apiKey': API_KEY,
'timeFrame': 'day',
'targetCalories': targetCalories.toString(),
'diet': diet,
};
Uri uri = Uri.https(
_baseUrl,
'/mealplanner/generate',
parameters,
);
Map<String, String> headers = {
HttpHeaders.contentTypeHeader: 'application/json',
};
try {
var response = await http.get(uri, headers: headers);
Map<String, dynamic> data = json.decode(response.body);
MealPlan mealPlan = MealPlan.fromMap(data);
return mealPlan;
} catch (err) {
throw err.toString();
}
}
当我运行该应用程序时,出现以下错误:E / flutter(6458):[错误:flutter / lib / ui / ui_dart_state.cc(171)]未处理的异常:无效的参数
[38; 5; 248mE / flutter(6458):#0 APIservice.generateMealPlan [39; 49m
E / flutter(6458):
似乎在将参数拼写为URL时遇到问题。我不确定是否正确编写了MAP参数和URI格式。
最佳答案
问题出在Meal
模型上。您使用的Meal
模型与api返回的模型不同:
我修复了Meal
模型,检查下面的代码:
class Meal {
int id;
String imageType;
String title;
int readyInMinutes;
int servings;
String sourceUrl;
Meal(
{this.id,
this.imageType,
this.title,
this.readyInMinutes,
this.servings,
this.sourceUrl});
Meal.fromMap(Map<String, dynamic> json) {
id = json['id'];
imageType = json['imageType'];
title = json['title'];
readyInMinutes = json['readyInMinutes'];
servings = json['servings'];
sourceUrl = json['sourceUrl'];
}
}
由于某些原因,该api似乎并未真正为相应的图像提供足够的支持,某些图像链接已断开。该应用程序的结果如下所示:
关于api - 如何在Flutter中使用Future和Uri.Https构造函数进行API调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63604483/