Home > Mobile >  The instance member 'currentPosition' can't be accessed in an initializer. with geolo
The instance member 'currentPosition' can't be accessed in an initializer. with geolo

Time:08-24

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!

CodePudding user response:

Define static to currentPosition, Thanks.

CodePudding user response:

You can use

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

  • Related