有没有办法在函数调用中仅在参数值不为空的情况下传递命名参数?
我有以下方法:
String concatenatesAddressData({String? city = 'Marília', String? state = 'São Paulo', String? country = 'Brasil'}) => ' - $city, $state, $country';
但是,我在参数中通知的值从API返回,该API可能提供数据,也可能不提供数据,因此我不能按如下方式传递参数,因为我可以将空值赋给其中一个参数:
String _dataPlace = concatenatesAddressData(city: place.country, state: place.state); // city and state are null
结果是:
" - null, null, Brasil"
有没有办法通知所有参数,如果它为空,就保持参数的缺省值,保持我使用的语法?
或者是否有必要更改方法,如下所示?
String concatenatesAddressData({city, state, country}) {
String _city = city ?? 'Marília';
String _state = state?? 'São Paulo';
String _country = country ?? 'Brasil';
return ' - $_city, $_state, $_country';
}