【问题标题】:Issue reading string http response in flutter在颤动中发出读取字符串http响应
【发布时间】:2021-11-08 09:02:15
【问题描述】:

我写了一个谷歌云function,它返回一个数字。我想在我的颤振应用程序上读到这个数字,但我做不到。貌似flutter http依赖只能读取JSON格式。

我已尝试在云函数中格式化响应输出,但我不断收到错误消息,提示未找到烧瓶。我正在使用 Python 3.9,根据this 链接,默认情况下应该有烧瓶。我也尝试将输出格式化为字典,然后使用json.dumps(x),但这也不起作用。

这个函数应该是检索数据:

  Future<http.Response> dataHTTP() async {
    return http.get(
      Uri.parse(
        ('https://us-east4-persuasive-yeti-325421.cloudfunctions.net/open_seats?college' +
            college.text.toUpperCase() +
            '&dept=' +
            department.text.toUpperCase() +
            '&course=' +
            course.text.toUpperCase() +
            '&section=' +
            section.text.toUpperCase()),
      ),
    );
  }

我想将输出打印到终端以检查一切是否正常。但是下面的代码 sn-p 返回以下内容:Instance of 'Future&lt;Response&gt;'

TextButton(
  onPressed: () async {
    print(dataHTTP().toString());
  },
  child: Text('Enter'),
)

如何返回数据本身而不是对象实例?在云函数中格式化输出,还是在客户端处理更容易?

【问题讨论】:

    标签: json flutter http flutter-web


    【解决方案1】:

    您收到 Instance of 'Future&lt;Response&gt;' 是因为您正在打印 Future 对象的 toString() 方法,而不是响应本身。 当您使用异步并且需要该异步任务的结果时,您需要“等待”它。 如果要保留方法签名,可以在 onPressed 函数中等待响应,如下所示:

    TextButton(
      onPressed: () async {
        http.Response response = await dataHTTP();
        print(response.body);
      },
      child: Text('Enter'),
    )
    

    您可以在this codelab 中获取有关使用 Dart 进行异步编程的更多信息

    【讨论】:

    • 感谢您的回复!尝试您的建议后,打印语句显示 'Instance of Response' 而不是数字编号。
    • 哦,你说得对,我的错,我认为响应类的“toString”被响应的标题和正文覆盖,不应该做出这样的假设。无论如何,很酷,你想通了!我将编辑我的答案,以便它适用于任何有同样问题的人
    【解决方案2】:

    我遇到的问题是 http 请求只包含一个整数值。为了在我的颤振应用程序上显示该值,我所要做的就是:

    TextButton(
      onPressed: () async {
        http.Response response = await dataHTTP();
        print(response.body);
      },
      child: Text('Enter'),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      • 1970-01-01
      • 2017-12-13
      • 2014-09-03
      相关资源
      最近更新 更多