首页 > 解决方案 > 无法在 Flutter 应用程序中加载当前位置

问题描述

我正在使用地理定位器插件并获取当前的纬度和经度,但我无法在我的 Flutter 应用程序的 initstate 中加载它。它显示渲染错误。

void initState() {
// TODO: implement initState
super.initState();
getCurrentLocation();

}

void getCurrentLocation() async {
var answer = await Geolocator().getCurrentPosition();
setState(() {
  latitude = answer.latitude;
  longitude = answer.longitude;
});

}

几毫秒后地图已更新为当前位置,但显示了这些错误。I/flutter (14143):══╡小部件库发现异常╞═════════════════════════════════════════════ ═════════════════════════

I/flutter (14143):在构建 HomePage(dirty, state: _HomePageState#d55de) 时抛出了以下断言:

I/flutter (14143): 'package:google_maps_flutter/src/location.dart': 断言失败: line 17 pos 16: 'latitude !=

I/flutter (14143): null': 不正确。

我/颤振(14143):

I/flutter (14143):要么断言表明框架本身有错误,要么我们应该提供大量

I/flutter (14143):此错误消息中的更多信息可帮助您确定和修复根本原因。

I/flutter (14143):无论哪种情况,请通过在 GitHub 上提交错误来报告此断言:

标签: google-mapsflutterdart

解决方案


我尝试了很多方法,直到我找到了这种方法,这要感谢一个在另一个颤振 facebook 小组上提供帮助的好心人。确保在您的 pubspec.yaml 中将位置更新为最新版本

dependencies: location: ^2.3.5 然后改成如下代码:

 
  LocationData _currentLocation;
  StreamSubscription<LocationData> _locationSubscription;

  var _locationService = new Location();
  String error;

  void initState() {
    super.initState();

    initPlatformState();

    _locationSubscription = _locationService
        .onLocationChanged()
        .listen((LocationData currentLocation) async {
      setState(() {
        _currentLocation = currentLocation;
      });
    });
  }

  void initPlatformState() async {
    try {
      _currentLocation = await _locationService.getLocation();


    } on PlatformException catch (e) {
      if (e.code == 'PERMISSION_DENIED') {
        error = 'Permission denied';
      }else if(e.code == "PERMISSION_DENIED_NEVER_ASK"){
        error = 'Permission denied';
      }
      _currentLocation = null;
    }
 Run code snippetReturn to post

您可以访问经度和纬度为

_currentLocation.longitude 和 _currentLocation.latitude

这些将返回双精度值。此外,还有更多可用的选项https://pub.dev/packages/location#-readme-tab-


推荐阅读