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

标签 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页面,该页面选择一个位置并应返回结果,如何使该函数等待结果?我不是在使用异步吗?

最佳答案

您可以使用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;
}

关于flutter - 在异步中等待而不是等待完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62380265/

相关文章:

animation - 英雄动画在 Flutter 中不起作用

flutter - 有什么方法可以从 Flutter 中的 DocumentSnapshot 获取 DocumentReference?

flutter - 如何在 Flutter 桌面应用程序(Linux)中配置窗口标题?

python - 处理来自 asyncmap 的结果

canvas - 更改 Canvas 上ImageElement的色调/色相

api - Flutter FutureBuilder 不断被调用

android-studio - 我的 flutter 项目在 android studio 中缺少 Gradle 窗口

与从 IDE 构建/运行相比,iOS 14 不允许 Flutter 应用程序(仍处于开发阶段)从主屏幕启动

node.js - 多个异步写入 Node 中的同一文件

c# - 在异步处理程序中最初将 handled 属性设置为 true 后,如何重新传播事件?