Khosraw Azizi
Khosraw Azizi

Reputation: 81

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!

Upvotes: 0

Views: 84

Answers (2)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63769

You can use

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

Upvotes: 1

Jenis Navadiya
Jenis Navadiya

Reputation: 196

Define static to currentPosition, Thanks.

Upvotes: 0

Related Questions