【问题标题】:Flutter - <asynchronous suspension> with geocoder packageFlutter - 带有地理编码器包的 <异步挂起>
【发布时间】:2021-03-07 03:48:17
【问题描述】:

我需要从经度和纬度中获取城市名称。 我没有找到一个包可以做到这一点,所以我使用 location 包来获取 Long 和 Lat 并使用 geocoder 来获取城市名称。

但我一直有这个错误并且没有结果:

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] 未处理的异常:PlatformException(failed, Failed, null, null)

控制台上的这个:

这是我的代码:

class _ProfileScreenState extends State<ExploreScreen> {
  dynamic currentLocation;
  double userLongitude;
  double userLatitude;
  Coordinates coordinates;
  var addresses;
  var first;

  @override
  initState() {
    super.initState();
    _getCurrentLongAndLat();
    _getCurrentPosition(userLatitude, userLatitude);
  }

  Future _getCurrentLongAndLat() async {
    currentLocation = LocationData;
    var error;
    var location = new Location();

    try {
      currentLocation = await location.getLocation();
      userLatitude = currentLocation.latitude;
      userLongitude = currentLocation.longitude;
      print('$userLatitude $userLatitude');
    } on PlatformException catch (e) {
      if (e.code == 'PERMISSION_DENIED') {
        error = 'Permission denied';
      }
      currentLocation = null;
    }
  }

  Future _getCurrentPosition(double long, double lat) async {
    coordinates = new Coordinates(userLatitude, userLongitude);
    addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
    print(addresses.first);
  }
}

【问题讨论】:

    标签: flutter dart flutter-packages


    【解决方案1】:

    我意识到颤振包地理定位器和位置有时会相互冲突。

    尝试使用地理定位器获取您的当前位置:

    Future _getCurrentPosition() async {
        Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high).then((Position position) {
          setState(() {
            _currentPosition = position;
            userLongitude = position.longitude;
            userLatitude = position.latitude;
            
          });
        });
      }
    

    这是一个 Future,因此您可以使用 await 真正等待结果,然后使用 userLat 和 userLng 调用 getAddress 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 2020-12-29
      相关资源
      最近更新 更多