【问题标题】:How to do an API call with Future and Uri.Https constructor in Flutter如何在 Flutter 中使用 Future 和 Uri.Https 构造函数进行 API 调用
【发布时间】:2020-12-15 15:47:51
【问题描述】:

尝试使用 Spoonacular API 构建食谱应用程序。尝试用谷歌搜索答案,但似乎 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

这在浏览器中完美运行,我需要将其转换为颤振代码:

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): [ERROR:flutter/lib/ui/ui_dart_state.cc(171)] 未处理异常:无效参数 [38;5;248mE/flutter (6458):#0 APIservice.generateMealPlan [39;49m E/颤动​​(6458):

在将参数拼接成 URL 时似乎遇到了问题。我不确定我是否正确编写了 MAP 参数和 URI 格式。

【问题讨论】:

  • 为什么apiKeyparameters 映射之前有一个?
  • @void 嘿,谢谢你的提问。我已经删除了它。这是我之前犯的一个错字,但我现在在我的代码中更正了它。我也会在这里编辑它。
  • 什么不起作用?你得到了什么?你期待什么?
  • @void 抱歉之前没有说清楚。我编辑了我的帖子,希望这次能清楚地解释我的问题。感谢您对此进行调查。
  • 如果parameters 映射中的diet 条目是none,请务必删除它,这可能是导致问题的原因。其他一切看起来都不错。

标签: api flutter dart


【解决方案1】:

问题出在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 似乎并未真正为各个图像提供足够的支持,一些图像链接已损坏。

应用结果如下所示:

【讨论】:

  • 你,我的先生....太棒了。感谢您的帮助。我会从这里弄清楚格式化的东西。谢谢!
猜你喜欢
  • 2021-12-19
  • 1970-01-01
  • 2021-07-13
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
  • 2021-07-07
  • 2020-01-21
相关资源
最近更新 更多