0

I use flutter and google maps

Geolocation is taken to show the current position of the user

The map loads correctly but before loading, it shows this error

'package:google_maps_flutter_platform_interface/src/types/location.dart': Failed assertion: line 19 pos 16: 'latitude != null': is not true.

this is the part of my code of init and getting the current position

var lat;
  var long;
  
  @override
  void initState()  {
    _child = SpinKitRipple(
      itemBuilder: (BuildContext context, int index) {
        return DecoratedBox(
          decoration: BoxDecoration(
            color: index.isEven ? Colors.grey : Color(0xffffb838),
          ),
        );
      },
    );
    
    getCurrentLocation();
    populateClients();
    setCustomMapPin();
    super.initState();
  }
  

  void getCurrentLocation() async {
     LocationPermission permission;
     

     permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.deniedForever) {
    lat=6.9271;long=79.8612;
  }

  else if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission != LocationPermission.whileInUse &&
        permission != LocationPermission.always) {
      lat=6.9271;long=79.8612;
    }
  }
    else{
      
      Position res = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high); //getCurrentPosition();
    
      lat=res.latitude;long=res.longitude;
      
    }
    
      
    
    
    setState(() {
      //position = res;
      //lat=6.9271;long=79.8612;
      _child = mapWidget();
    });
  }

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.white),
        title: Text('Map'),
        centerTitle: true,
        backgroundColor: Colors.blue,
      ),
      body: mapWidget(),
    );
  }

  Widget mapWidget() {
    return Stack(
      children: <Widget>[
        GoogleMap(
          initialCameraPosition: CameraPosition(
            target: LatLng(lat,long),//(position.latitude, position.longitude),
            zoom: 18,
          ),

          ///mapType: MapType.normal,
          onMapCreated: (GoogleMapController controller) async{
            _controller = controller;
            await setMapStyle(controller, context);
          },

          markers: Set<Marker>.of(markers.values),
          compassEnabled: true,
          myLocationEnabled: true,
        ),
        SizedBox(
          height: 26,
        ),
      ],
    );
  }
}

** I would like to display an animation until the map is correctly loaded**

coder
  • 37
  • 7

1 Answers1

1

Whenever you are rendering UI, that depends on waiting for another operation to complete, you must use a FutureBuilder widget.

https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

In order to do what you are trying to do, you must wrap your current widget with a FutureBuilder. Like So:

      Future<Widget> reloadCurrentLocation;
    
      @override
      void initState() {
        super.initState();
    
        reloadCurrentLocation = getCurrentLocation();
      }
    
      Future<Widget> getCurrentLocation() async {
         LocationPermission permission;
         
         permission = await Geolocator.checkPermission();
         if (permission == LocationPermission.deniedForever) {
           lat=40.7128;long=74.0060;
         }
    
         else if (permission == LocationPermission.denied) {
           permission = await Geolocator.requestPermission();
         if (permission != LocationPermission.whileInUse &&
            permission != LocationPermission.always) {
            lat=40.7128;long=74.0060;
            }
        }
        else {
          Position res = await Geolocator.getCurrentPosition(desiredAccuracy: 
          LocationAccuracy.high); //getCurrentPosition();
        
          lat=res.latitude;
          long=res.longitude;          
        }
        
        populateClients();
        setCustomMapPin();
          
        return _child = mapWidget();
    }
        
    
    
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.white),
        title: Text('Map'),
        centerTitle: true,
        backgroundColor: Colors.blue,
      ),
      body: mapWidget(),
    );
  }

  Widget mapWidget() {
    return FutureBuilder(
                future: reloadCurrentLocation,
                builder: (context, state) {
                  if (state.connectionState == ConnectionState.active ||
                      state.connectionState == ConnectionState.waiting) {
                      return SpinKitRipple(
                        itemBuilder: (BuildContext context, int index) {
                          return DecoratedBox(
                               decoration: BoxDecoration(
                               color: index.isEven ? Colors.grey : 
                                    Color(0xffffb838),
                               ),
                          );
                        },
                      );
                  } else {
                      return Stack(
                        children: <Widget>[
                         GoogleMap(
                           initialCameraPosition: CameraPosition(
                           target: 
                           LatLng(lat,long),//(position.latitude, 
                           position.longitude),
                           zoom: 18,
                         ),

                         ///mapType: MapType.normal,
                         onMapCreated: (GoogleMapController 
                           controller) async{
                             _controller = controller;
                             await setMapStyle(controller, context);
                        },

                       markers: Set<Marker>.of(markers.values),
                       compassEnabled: true,
                       myLocationEnabled: true,
                       ),
                       SizedBox(
                        height: 26,
                       ),
                      ],
                     );
                });
  }
}
Dan Gerchcovich
  • 506
  • 4
  • 8
  • When i add it an error comes at `@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( iconTheme: IconThemeData(color: Colors.white), title: Text('Map'), centerTitle: true, backgroundColor: Colors.blue, ), body: mapWidget(), ); }` build gets underlined – coder Feb 06 '21 at 09:28
  • Ah, I thought that you abstracted the map code in its own widget. You need to add the FutureBuilder code into the mapWidget method. The mapWidget() needs to return the FutureBuiider – Dan Gerchcovich Feb 06 '21 at 09:38
  • Can you please update the answer with what i should do im really new to flutter and still learning; i have also updated the code with all the main parts – coder Feb 06 '21 at 10:22
  • updated. Please check again – Dan Gerchcovich Feb 06 '21 at 10:41
  • Thank you it worked, if i want to put a loading animation i just need to replace `return SpinKitRipple` right ? – coder Feb 06 '21 at 10:46
  • yes. Glad to see this worked for you. Can you please mark my post as the answer, and give it an upvote? – Dan Gerchcovich Feb 06 '21 at 10:47
  • I'm aiming for 10000 points by end of the year. It's like a marathon, I'm running on my keyboard – Dan Gerchcovich Feb 06 '21 at 10:48
  • Done Best of Luck and thank you again for the descriptive approach – coder Feb 06 '21 at 10:54