Unable to get latitude and longitude user - Flutter

Viewed 33

I am using google_maps_flutter: ^2.2.0 and geolocator: ^9.0.1 and trying to get user latitude and longitude by running this code from geolocator package:

Position posisiNow = await Geolocator.getCurrentPosition(
            desiredAccuracy: LocationAccuracy.high);

The problem is... I always getting error when trying to reach posisiNow.latitude or posisiNow.longitude but when I only print posisiNow I get good result:Latitude: 37.33233141, Longitude: -122.0312186. The error when I try to print posisiNow.latitude is: NoSuchMethodError: The getter 'latitude' was called on null. I need that data because I need to put latitude and longitude in this function of google_maps_flutter:

controllerNow.animateCamera(CameraUpdate.newCameraPosition(
              CameraPosition(
                  bearing: 192.8334901395799,
                  target: LatLng(posisiNow.latitude, posisiNow.longitude),
                  tilt: 0,
                  zoom: 16.00)));

This problem only in ios Simulator, I have tried in android and worked fine. I also open this question in https://github.com/Baseflow/flutter-geolocator/issues/1135

1 Answers

Here target: LatLng(posisiNow.latitude, posisiNow.longitude), the latitude and longitude cannot be null. You can either provide default fallback values . target: LatLng(posisiNow.latitude ?? 0.0, posisiNow.longitude ?? 0.0), you need to make Position? nullable.

Also you can get location before building this widget. eg in init state.

Related