0

I want to load my google maps on flutter app to my current location.

the code i used is..

late LatLng _center;
  late Position currentLocation;

  @override
  void initState() {
    super.initState();
    getUserLocation();
  }

  Future<Position> locateUser() async {
    return Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
  }

  getUserLocation() async {
    currentLocation = await locateUser();
    setState(() {
      _center = LatLng(currentLocation.latitude, currentLocation.longitude);
    });
    print('center $_center');
  }
  static const CameraPosition _MyPostn = CameraPosition(
    target:_center,
    zoom: 14.4746,
  );

But I'm getting error as enter image description here

What am I doing wrong here?

I did search other similar questions but didn't find any solution.

SaFaL
  • 31
  • 6

1 Answers1

1

You need location permission to access the GPS location. Assuming you have taken care of the permission(if not, please check the link below)

geolocator 9.0.2

You could you try like this

define _MyPostn as late.

Initialise _MyPostn once you get _center.

late LatLng _center;
late Position currentLocation;
late CameraPosition _MyPostn;
bool isLoading = true;

@override
  void initState() {
    super.initState();
    getUserLocation();
}

Future<Position> locateUser() async {
    return Geolocator.getCurrentPosition(
    desiredAccuracy: LocationAccuracy.high);
}

getUserLocation() async {
    currentLocation = await locateUser();
    setState(() {
      _center = LatLng(currentLocation.latitude, currentLocation.longitude);
    });
    print('center $_center');
    _MyPostn = CameraPosition(target:_center, zoom: 14.4746,);
    isLoading = false;
}
  • when running the app, it shows an error screen for a couple seconds and then loads the map. The error screen showed "LateInitializationError : Field _MyPostn575457168 has not been initialized." – SaFaL Mar 28 '23 at 04:59
  • You could manage this error screen by adding a conditional statement in the widget tree and show a circularProgessIndicator until the variable _MyPostn is initialised – Niladri Raychaudhuri Mar 28 '23 at 10:55
  • Cool. what should the condition be? – SaFaL Mar 28 '23 at 11:33
  • 1
    check the modified code, added isLoading variable. Inside Scaffold you may check the variable like body: isLoading ? const Center( child: CircularProgressIndicator(), ) : FinalWidgetToDisplay(), – Niladri Raychaudhuri Mar 28 '23 at 11:59