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

Flutter - Keep default value of named parameter when sent parameter is null

提问人:Massau 提问时间:6/28/2023 更新时间:6/28/2023 访问量:31

问:

有没有办法在函数调用中传递命名参数,以防参数值不为空?

我有以下方法:

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

但是,我在参数中通知的值是从可能提供数据也可能不提供数据的 API 返回的,因此我无法按如下方式传递参数,因为我可以将 null 值分配给其中一个参数:

String _dataPlace = concatenatesAddressData(city: place.country, state: place.state); // city and state are null

导致:

" - null, null, Brasil"

有没有办法通知所有参数,如果它为 null,则保持参数的默认值,保持我使用的语法?

还是有必要更改方法如下?

String concatenatesAddressData({city, state, country}) {
    String _city = city ?? 'Marília';
    String _state = state?? 'São Paulo';
    String _country = country ?? 'Brasil';

    return ' - $_city, $_state, $_country';
}
Flutter dart 命名参数

评论


答:

1赞 Ivo 6/28/2023 #1

你不需要使用中间变量,可以

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

评论

0赞 Massau 6/28/2023
有道理,我没想到!感谢您的回复