【问题标题】:Await in Async not waiting to Completion异步等待不等待完成
【发布时间】:2020-10-04 09:29:19
【问题描述】:

我已通读Async/Await/then in Dart/Flutter,试图了解为什么我的aysnc 函数中的await 不会等到完成后再继续。在我的 UI 中,有一个按钮调用异步方法返回位置,位置始终返回 null 并且不等待函数完成。

   onChanged: (newValue) async {
      setState(() {
        _selectedLocation = newValue;
      });
      if (_selectedLocation == "Set Location") {
        location = await runPlacePicker(context);    // <- Calling the method here
        _selectedLocationText = location.lat.toString();
      }

  Future<Location> runPlacePicker(context) async {   // <- Should return a Location value after popup
    Timer _throttle;
    PlacePicker result;
    Location location;
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => PlacePicker(
                  apiKey: "",
                  onPlacePicked: (result) {
                    print(result.formattedAddress);
                    Navigator.of(context).pop();
                    location = result.geometry.location;
                    return location;
                  },
                  initialPosition: LatLng(0,0),
                  resizeToAvoidBottomInset: true,
                  useCurrentLocation: true,
                )
        )
    );
    if (location == null) {
      return null;
    } else {
      return location;
    }
  }

该函数将调用推送到一个新的 UI 页面,该页面选择了一个位置并应该返回一个结果,我怎样才能让该函数等待结果?我没有使用异步吗?

【问题讨论】:

  • 我在runPlacePicker中没有看到任何异步指令
  • 在选择地点之前你是否得到了空值?
  • @jitsm555 是的,在我可以选择地点之前,我得到了空值,稍后将在下面尝试 Crizant 的答案并回复
  • @num8er Future runPlacePicker 是一个异步方法

标签: flutter asynchronous dart async-await


【解决方案1】:

您可以使用Navigator.of(context).pop(location)PlacePicker 返回结果。

代码可以简化为:

Future<Location> runPlacePicker(context) async {
  final Location location = await Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => PlacePicker(
        apiKey: "",
        onPlacePicked: (result) {
          Navigator.of(context).pop(result.geometry.location);
        },
        initialPosition: LatLng(0,0),
        resizeToAvoidBottomInset: true,
        useCurrentLocation: true,
      )
    )
  );
  return location;
}

【讨论】: