OhMad
OhMad

Reputation: 7299

Dart - HttpRequest.getString() return JSON

I am trying to return the raw JSON from my server path (I use rpc for the API) with a Closure, because I want to keep it in the same function instead of using .then() and calling another one.

This is my code:

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

  getRawJson(String response){
    return response;
  }

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

then in my main function I do this:

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

By doing so I get this error:

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

Did I use Closures wrong? Is there maybe a way to return the actual raw Json inside of .then() instead of calling another function?

Thanks in advance

Upvotes: 2

Views: 525

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658235

Not sure what you try to accomplish. What is return getRawJson; supposed to do?

getRawJson just returns a reference to the getRawJson method. When you use getRawJson

print(getRawJson());

calls getRawJson without a parameter, but it expects String response. This is why you get the error message.

You can't avoid using then. Alternatively you can use async/await

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

  getRawJson(String response){
    return response;
  }

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

main

GetEntryDiscussionsFromDb()
.then(print);

or

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

Upvotes: 2

Related Questions