【问题标题】:Flutter - Geolocator.getCurrentPosition never returnsFlutter - Geolocator.getCurrentPosition 永远不会返回
【发布时间】:2021-12-29 05:50:44
【问题描述】:

我正在 Flutter 上使用 Google 地图 API,而 Geolocator.getCurrentPosition 永远不会返回。 这是我的代码(主要取自 Simone Alessandria 的 Flutter Projects,并从网络上进行了一些更改以试图解决此问题)

Future _getCurrentLocation() async {
    bool isGeolocationAvailable = await Geolocator.isLocationServiceEnabled();
    if (isGeolocationAvailable) {
      try {
          Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best, timeLimit: Duration(seconds: 10)).then((pos) {
          setPosition(pos);
        });
      } catch (error) {
        print(error.toString());
        Geolocator.getLastKnownPosition().then((pos) {
          setPosition(pos);
        });
      }
    }
    return null;
  }

正如我提到的 Geolocator.getCurrentPosition 永远不会返回,至少我得到一个例外的时间限制。

这是我的 Flutter 医生以防万一:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.5.1, on Ubuntu 20.04.3 LTS 5.11.0-38-generic, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.1)
[✓] Android Studio (version 4.1)
[✓] VS Code
[✓] Connected device (1 available)

• No issues found!

还有版本

environment:
  sdk: ">=2.14.2 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3
  google_maps_flutter: ^2.0.10
  permission_handler: ^8.1.6
  geolocator: ^7.7.0

我在像素模拟器中运行

谢谢!

【问题讨论】:

    标签: android flutter google-maps future


    【解决方案1】:

    这可能与您在收集位置时使用的距离过滤器有关。这可能会发生,因为当您打开应用程序时,它会使用 currentLocation。然后,当您想再次获取电流时,过滤器会检测到位置太近并且不会传递它。在我的应用程序中,我首先尝试 getLastKnowPosition,然后当它为 null 时,我从 getCurrentPosition 获取它。

    【讨论】:

    • 谢谢!我已经尝试过了,我可能会将代码切换回它,因为它很有意义。但是,我在模拟器中进行了冷启动并关闭并重新打开位置,它开始工作了。
    猜你喜欢
    • 2019-11-15
    • 2011-07-25
    • 1970-01-01
    • 2012-10-02
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多