Search code examples
firebasefluttergoogle-mapslocationgeopoints

need to add current location to firestore with nullsaftey in flutter


I use the packages below:

google_maps_flutter: 
cloud_firestore: ^2.4.0
location: ^4.2.0

I have this code:

storUserLocation()async{
       Location location = new Location();
    
    location.onLocationChanged.listen((LocationData currentLocation) {
      
      FirebaseFirestore.instance.collection('parking_location').add({
      
        'location' : GeoPoint(currentLocation.latitude, currentLocation.longitude)
        
      }); 

And it returns this error.


Solution

  • LocationData.longitude and LocationData.latitude returns double? which means the return values could be null.

    You can get rid of the errors by adding a check to ensure that the values are not null before you use them. Checkout below:

    location.onLocationChanged.listen((LocationData currentLocation) {
     
      if (currentLocation.latitude != null && currentLocation.longitude != null) {     
          FirebaseFirestore.instance.collection('parking_location').add({
            'location' : GeoPoint(currentLocation.latitude, currentLocation.longitude)
          }); 
      }
    }
    

    Read more on null safety here.