How can I get result of async call before continuing execution in a synchronous method. For example,
main(List<String> arguments) {
String r;
value().then((s) => r = s);
print(r); // prints 'null', how to get 'foo'?
}
Future<String> value() async {
return await "foo";
}
I know I can mark main async and call await value()
but I want main to stay sync. Any idea how to do this?
More concrete example,
class MyWidget extends StatefulWidget {
@override
MyWidgetState createState() => MyWidgetState();
}
class MyWidgetState extends State<MyWidget> {
String emp;
MyWidgetState() {
emp = getEmployee(); // this needs to be called with await
}
@override
Widget build(BuildContext context) {
// use 'emp' to build widget
}
}
static Future<String> getEmployee() async {
var response = await http.get(url);
if (response.statusCode != 200) {
throw HttpException("read error");
}
return response.body;
}