Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Google Maps doesn´t wait to Location

I´m trying to show a map with current location. For do this i used Location and Google Map plugins (last version).

I have a code similar to:

var lng, lat;

          @override
          initState() {
            super.initState();
            loading = true;
            getLocation();
          }

              Future getLocation() async {
                    final location = Location();
                    var currentLocation = await location.getLocation();
                    setState(() {
                      lat = currentLocation.latitude;
                      lng = currentLocation.longitude;
                      loading=false;
                    });
                  }

             loading==false ? GoogleMap(
                 mapType: MapType.hybrid,
                 myLocationButtonEnabled: true,
                 myLocationEnabled: true,
                 initialCameraPosition: CameraPosition(
                      target: LatLng(lat, lng),
                      zoom: 15.0,
                            )):null,

When we go the view with map a error appear around 1s (then view load properly) with this error in the console

I/flutter (15567): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ I/flutter (15567): The following assertion was thrown building HomePageScreen(dirty, dependencies: I/flutter (15567): [_LocalizationsScope-[GlobalKey#78c30], MediaQuery], state: _HomePageScreen#9c9d2): I/flutter (15567): 'package:google_maps_flutter/src/location.dart': Failed assertion: line 17 pos 16: 'latitude != I/flutter (15567): null': is not true.

I debug it and the error is relative simple: The Location plugin load latitude and longitude slow , Google Maps plugin load more fast. So we have a error.

The question is: How can i force Google map to wait location and longitude from Location plugin?

like image 558
El Hombre Sin Nombre Avatar asked Sep 04 '26 03:09

El Hombre Sin Nombre


1 Answers

Show an empty Container() or any loading indicator while your lat and lng is null.

lat == null || lng == null
  ? Container()
  : GoogleMap(
      mapType: MapType.hybrid,
      myLocationButtonEnabled: true,
      myLocationEnabled: true,
      initialCameraPosition: CameraPosition(
        target: LatLng(lat, lng),
        zoom: 15.0,
      ),
    );
like image 132
Michael Yuwono Avatar answered Sep 05 '26 18:09

Michael Yuwono



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!