需要在flutter中使用nullsafety将当前位置添加到firestore

问题描述

我使用以下软件包:

google_maps_Flutter: 
cloud_firestore: ^2.4.0
location: ^4.2.0

我有这个代码

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

它返回 this error

解决方法

LocationData.longitudeLocationData.latitude 返回 double?,这意味着返回值可能为空。

您可以通过添加检查来消除错误,以确保在使用之前这些值不为空。结帐如下:

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

阅读有关空安全 here 的更多信息。