【问题标题】:Dart - HttpRequest.getString() return JSONDart - HttpRequest.getString() 返回 JSON
【发布时间】:2017-04-10 10:09:20
【问题描述】:

我正在尝试使用闭包从我的服务器路径(我使用 rpc 作为 API)返回原始 JSON,因为我想将其保留在同一个函数中,而不是使用 .then() 并调用另一个函数。

这是我的代码:

GetEntryDiscussionsFromDb(){
  var url = "http://localhost:8082/discussionApi/v1/getAllDiscussions";

  getRawJson(String response){
    return response;
  }

  HttpRequest.getString(url).then(getRawJson);
  return getRawJson;
}

然后在我的主要功能中我这样做:

var getRawJson = GetEntryDiscussionsFromDb();
print(getRawJson());

这样做我得到这个错误:

G.GetEntryDiscussionsFromDb(...).call$0 is not a function

我用错了闭包吗?有没有办法在 .then() 中返回实际的原始 Json 而不是调用另一个函数?

提前致谢

【问题讨论】:

    标签: json api server dart


    【解决方案1】:

    不确定您尝试完成什么。 return getRawJson; 应该做什么?

    getRawJson 只是返回对getRawJson 方法的引用。当你使用getRawJson

    print(getRawJson());
    

    在没有参数的情况下调用getRawJson,但它需要String response。这就是您收到错误消息的原因。

    您无法避免使用then。或者你可以使用async/await

    GetEntryDiscussionsFromDb(){
      var url = "http://localhost:8082/discussionApi/v1/getAllDiscussions";
    
      getRawJson(String response){
        return response;
      }
    
      return HttpRequest.getString(url).then(getRawJson);
    }
    

    主要

    GetEntryDiscussionsFromDb()
    .then(print);
    

    main() async {
      ...
      var json = await GetEntryDiscussionsFromDb();
      print(json);
    }
    

    【讨论】:

    • 哦,不知道从 main 调用我的 GetEntryDiscussionsFromDb 时可以使用...谢谢 :)
    • then() 返回一个Future,您可以再次在该Future 上调用then
    猜你喜欢
    • 2019-02-07
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多