Khader Murtaja
Khader Murtaja

Reputation: 445

Flutter - <asynchronous suspension> with geocoder package

I need to get the city name from Longitude and Latitude. I do not found a single package to do that, so I use location package to get Long and Lat and used geocoder to get the city name.

But I keep have this error and have no result :

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: PlatformException(failed, Failed, null, null)

and this one after it on the console: < asynchronous suspension >

Here is my code :

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);
  }
}

Upvotes: 0

Views: 1953

Answers (1)

justin0060
justin0060

Reputation: 93

I realized flutter packages geolocator and location conflict with each other sometimes.

Try using geolocator to get your current position:

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

It is a Future, so you can use await to really wait for results and after that call the getAddress function with the userLat and userLng.

Upvotes: 0

Related Questions