Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'}';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading