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

Is there any way to pass a named parameter in a function call just in case the parameter value is not null?

I have the following method:

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

However, the values that I inform in the parameters return from an API that may or may not provide data, so I cannot pass the parameters as below, because I can assign a null value to one of the parameters:

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

Resulting in:

" - null, null, Brasil"

Is there any way, informing all the parameters, in case it is null, to maintain the default value of the parameter, maintaining the syntax that I use?

Or would it be necessary to change the method as below?

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

    return ' - $_city, $_state, $_country';

>Solution :

You wouldn’t need to use intermediate variables and can do

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

Leave a Reply