简体   繁体   中英

Dart Default Nullable Parameters

I've recently been migrating my Flutter/Dart apps to be null safety compatible/sound. To this end I came across a situation I can't really figure out a 'best practice' for.

I have a few functions similar to the following:

String defaultErrorMessage({String? message = 'Please try again later.'}) {
  return "Error. $message";
}

Fairly straightforward - just meant to standardize error messages and provide a default one for situations where there may not be an error message.

The question is this:

The parameter 'message' is not required and has a default value. If I pass it a null string it will simply print "Error. null" - this is shown in this dartpad

Is there a simple way or special syntax I should be using for default parameters? I recognize there are simple ways to rewrite this I feel like I shouldn't have to - isn't the point of all these null features/checks to automatically do things like this? Specifically I could do the following:

String defaultErrorMessage({String? message}) {
  message ??= 'Please try again later.';
  return "Error. $message";
}

But I'd much prefer to handle that in the function definition itself.

Thank you in advance for the help!

So basically, you want to make it so that if you pass a null value, it uses the default message you have set? I am sorry to say that the code you already posted is probably the best to do that.

But if you want null values to be the same as passing no value, why even make the variable nullable at all? Would it not make more sense to do something like this?

String defaultErrorMessage({String message = 'Please try again later'}) {
  return "Error. $message";
}

Which will of course give you some compilation errors if someone did something like this:

defaultErrorMessage(message: null);

so you will have to go to every time this happened and change it to

defaultErrorMessage();

But well, that's kinda how null safety migration has always gone for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM