Search code examples
flutterdartlocation

The instance member 'currentPosition' can't be accessed in an initializer. with geolocator when trying to get position


I've been trying to get the user's current location on Android, but I'm struggling to get it to work because of an instance initialization error. I'm using the following code right now to get the user's latitude and longitude into a variable.

Position? currentPosition;

  final Geolocator geolocator = Geolocator();
  void _getCurrentLocation() {
    Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
        .then((Position position) {
      setState(() {
        currentPosition = position;
      });
    }).catchError((e) {
      print(e);
    });
  }

  late GoogleMapController myMapController;
  final Set<Marker> _markers = {};
  static final LatLng _mainLocation =
      LatLng(currentPosition!.latitude, currentPosition!.longitude);

I've tried using Future and different ways of formatting the function, but I run into an issue one way or another. Any particular way I can get this to work? Thank you!


Solution

  • You can use

      final Set<Marker> _markers = {};
      late final LatLng _mainLocation =
          LatLng(currentPosition!.latitude, currentPosition!.longitude);