Reputation: 781
I'm learning Dart and I've hit a roadblock. I very much want to return a value from a json string processing function so I can use that value inside main(). (I'm trying to set some top-level variables to use with a one-way data bind with an html template.) I'm using HttpRequest.getString
and a .then
call to kick off the processing. But HttpRequest doesn't like being assigned to a variable so I'm not sure how to get anything back out of it.
processString(String jsonString) {
// Create a map of relevant data
return myMap;
}
void main() {
HttpRequest.getString(url).then(processString);
// Do something with the processed result!
}
I guess my question is how do I get a value back from a function that was called from an HttpRequest?
Upvotes: 1
Views: 623
Reputation: 34031
You're trying to do something that the Dart async model doesn't support. You'll have to handle the result of the async request:
processString()
,processString()
,then()
. Or something similar. What you can't do is access it from further down in main()
:
processString(String jsonString) {
// Create a map of relevant data
// Do something with the processed result!
}
void main() {
HttpRequest.getString(url).then(processString);
// Any code here can never access the result of the HttpRequest
}
You may prefer:
processString(String jsonString) {
// Create a map of relevant data
return myMap;
}
void main() {
HttpRequest.getString(url).then((resp) {
map = processString(resp);
// Do something with the processed result!
});
// Any code here can never access the result of the HttpRequest
}
Upvotes: 2