Flutter -当发送的参数为空时,保留命名参数的默认值

dzjeubhm  于 2023-06-30  发布在  Flutter
关注(0)|答案(1)|浏览(139)

有没有办法在函数调用中传递一个命名参数,以防参数值不为null?
我有以下方法:

String concatenatesAddressData({String? city = 'Marília', String? state = 'São Paulo', String? country = 'Brasil'}) => ' - $city, $state, $country';

然而,我在参数中通知的值从可能提供或可能不提供数据的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';
}
suzh9iv8

suzh9iv81#

您不需要使用中间变量,并且可以

String concatenatesAddressData({String? city, String? state, String? country}) => ' - ${city ?? 'Marília'}, ${state ?? 'São Paulo'}, ${country ?? 'Brasil'}';

相关问题