api - 如何在Flutter中使用Future和Uri.Https构造函数进行API调用

标签 api flutter dart

尝试使用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似乎并未真正为相应的图像提供足够的支持,某些图像链接已断开。
该应用程序的结果如下所示:
enter image description here

关于api - 如何在Flutter中使用Future和Uri.Https构造函数进行API调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63604483/

相关文章:

flutter - 一旦应用程序从权限设置屏幕返回,Flutter应用程序中的空白屏幕

cocoa - Delphi 有哪些好的 Cocoa API 端口

api - 错误 Telegram ID 和哈希 "Incorrect app name&#33"

api - YouTube播放列表ID

flutter - 如何在 Flutter 中使文本响应?

dart - 无状态小部件会自行处置吗?

arrays - 当旋转木马上方时,为什么不能滚动列表?

flutter - 如何将 float Action 粘贴到底部 flutter (底部对齐)

android - 当从图像选择器打开相机时,应用程序 "Lost connection to device."

linux - 用于 Linux 进程监控的 Python Zabbix API