在 null 上调用了 getter 'placeName'

时间:2020-12-21 13:00:52

标签: android ios flutter dart hybrid-mobile-app

我用以下字符串创建了一个类地址

class Address{
  String placeName='';
  double latitude;
  double longitude;
  String placeId= '';
  String placeFormattedAddress= '';
  Address(
      {
        this.placeId,
        this.latitude,
        this.longitude,
        this.placeName,
        this.placeFormattedAddress,
      });

}

我尝试从谷歌地图获取地址,然后使用提供程序包传递值

class HelperMethods{
  static Future<String> findCordinateAddress(Position position, context) async {

    String placeAddress = '';

    var connectivityResult = await Connectivity().checkConnectivity();
    if(connectivityResult != ConnectivityResult.mobile && connectivityResult != ConnectivityResult.wifi){
      return placeAddress;
    }

    String url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.latitude},${position.longitude}&key=$mapKey';

    var response = await RequestHelper.getRequest(url);

    if(response != 'failed'){
      placeAddress = response['results'][0]['formatted_address'];

      Address pickupAddress = new Address();
      pickupAddress.longitude = position.longitude;
      pickupAddress.latitude = position.latitude;
      pickupAddress.placeName = placeAddress;

      Provider.of<AppData>(context, listen: false).updatePickupAddress(pickupAddress);

    }

    return placeAddress;

  }

}

但问题是这需要一些时间 因此,当我尝试打开将显示地址的页面时,它会显示错误 并且在地址准备好后它就消失了,那么有没有办法防止这种情况发生? 传递不同的值直到地址准备好???

getter 'placeName' 在 null 上被调用。 接收器:空 尝试调用:placeName

    String address = Provider.of<AppData>(context).pickupAddress.placeName ?? '';

and then I print or display the content of the address 

2 个答案:

答案 0 :(得分:0)

您可能希望在 UI 代码中使用条件。类似的东西:

if(placeName != null)
  Text(placeName)

// null-aware operator
Text(placeName ?? "name is null")

// ternary operator
placeName != null ? Text(placeName) : CircularProgressIndicator()

答案 1 :(得分:0)

更新: 这很容易,但我以前看不到 只需在 .pickupaddress 后添加问号 (?)

String address = Provider.of<AppData>(context).pickupAddress?.placeName ?? '';