在异步中等待而不是等待完成

时间:2020-06-15 01:59:35

标签: flutter asynchronous dart async-await

我已通读Async/Await/then in Dart/Flutter来尝试理解为什么aysnc函数中的await不等到完成才继续前进。在我的UI中,有一个按钮,该按钮调用async方法以返回位置,该位置始终返回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页面,该页面选择一个位置并应返回结果,如何使该函数等待结果?我不使用异步功能吗?

1 个答案:

答案 0 :(得分: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;
}
相关问题