how to get user current position as initial location in flutter google maps

Issue

I am trying to get my current position as my initial position in google maps flutter.. but I always get error that says like this…initialCameraPosition !=null is not true so far I have tried using async await to get my current location.. here is the code

static LatLng _initialPosition;

@override
  void initState() {
    _getLocation();
    super.initState();
  }
void _getLocation() async {
    LocationData currentLocation;
    currentLocation = await location.getLocation();
    setState(() {
      _initialPosition =
          LatLng(currentLocation.latitude, currentLocation.longitude);
    });
  }

static final CameraPosition initialLocation = CameraPosition(
    target: _initialPosition,
    zoom: 14.4746,
  );

is there something that I need to add from my code?
and here is my widget

GoogleMap(
            mapType: MapType.normal,
            initialCameraPosition: initialLocation,
            markers:...,
            circles:...,
            onMapCreated: (GoogleMapController controller) {
              _controller = controller;
            },
          ),

Solution

_getLocation is an async function. It may not have populated _initialPosition when you start GoogleMap.

Give _initialPosition a starting value and then update GoogleMap when _initialPosition has been updated.

Answered By – Glen

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *