need to add current location to firestore with nullsaftey in flutter

572 Views Asked by At

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.

1

There are 1 best solutions below

0
Victor Eronmosele On BEST ANSWER

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.