如何阻塞直到异步功能完成

时间:2019-06-09 20:53:52

标签: flutter dart

在以同步方法继续执行之前,如何获得异步调用的结果。例如,

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";
}

我知道我可以标记主要异步并调用await value(),但我希望主要保持同步。知道怎么做吗?

更具体的例子,

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;
}

0 个答案:

没有答案