0

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;
}
danze
  • 745
  • 2
  • 10
  • 24
  • Why don't you want to make `main` `async`? What are you trying to accomplish? `main` is the only function where there shouldn't be any consequences of marking it `async` because there are no callers to propagate the asynchrony to. – jamesdlin Jun 09 '19 at 21:08
  • @jamesdlin I'm just using main here as example. But I run in to similar issue in a class method that's overriding a super class and I can't change the method signature in the super class. – danze Jun 09 '19 at 21:30
  • what about `value().then((s) {r = s; print(r);});`? – Jacob Phillips Jun 09 '19 at 22:49
  • 2
    There is no way to block. Dart isolates are single-threaded, so blocking means that the thing you're waiting on won't be able to execute at all. Basically this is a duplicate of https://stackoverflow.com/questions/28238161/how-to-make-an-asynchronous-dart-call-synchronous – jamesdlin Jun 09 '19 at 22:49
  • Also, if you have a more specific example of what you're trying to do, we might be able to help you accomplish that. – jamesdlin Jun 09 '19 at 22:54
  • I'm trying to build flutter widget state using data from server that is retrieved asynchronously. I added sample code above. – danze Jun 09 '19 at 23:12
  • 2
    Then you should use [`FutureBuilder`](https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html) or [`StreamBuilder`](https://api.flutter.dev/flutter/widgets/StreamBuilder-class.html). – jamesdlin Jun 09 '19 at 23:40

0 Answers0