Reputation: 11
I'm trying this in Dart:
import 'dart:convert';
import 'dart:html';
class testHandler {
Map parsedJSON;
testHandler();
void Initialize(){
String rawJSON = "core/testConfiguration.json";
HttpRequest.getString(rawJSON)
.then((String f) => parsedJSON.from(JSON.decode(f)))
.catchError((Error e) => print(e.toString()));
print(parsedJSON);
}
}
If you see I'm setting parsedJSON
in .then()
but when I'm trying to get the var, it returns null.
Upvotes: 1
Views: 73
Reputation: 975
No, you are not setting parsedJSON
in .then()
. You are trying to call method from null object. Before use parsedJSON
you should set it with =
operator, like
parsedJSON = new Map.from(JSON.decode(f));
In other words, you mixed up parsedJSON's methods and Map's constructors.
P.S. And, as Gunter denoted it, you may write it shortly:
parsedJSON = JSON.decode(f);
Upvotes: 0
Reputation: 657506
print(parsedJSON);
is executed before getString()
returns. getString()
is async and the callback passed to then()
will be executed sometimes later after getString()
returned the result but print(parsedJSON);
will be executed immediately.
Using async
/await
makes this quite easy:
import 'dart:convert';
import 'dart:html';
class testHandler {
Map parsedJSON;
testHandler();
Future Initialize() async {
String rawJSON = "core/testConfiguration.json";
try {
String f = await HttpRequest.getString(rawJSON);
parsedJSON = JSON.decode(f);
} catch(Error e) {
print(e.toString());
}
print(parsedJSON);
}
}
Async is contagious therefore code calling Initialize()
has to wait for it to finish as well.
Upvotes: 2