Are optional parameters in null-safe dart automatically nullable? If no, is there an easy way to make my code null-safe?


I noticed a few more users on the Dart/Flutter tags trying out null safety in the newer Dart SDK versions and I started reading up about it, starting with this Medium article.

I noticed that in all of their examples they use positional, required arguments. But how will null-safety work with optional parameters, both positional and named?

Optional parameters are inherently null so does this mean that all optional parameters will have to be declared with the nullable variable declaration syntax with null-safety enabled? It seems like only a minor inconvenience to add ?, but it could break a lot of code that uses optional parameters liberally. Will dart be able to make an exception for optional parameters(knowing that they will always be nullable) so that such large changes can be avoided? or is there an easier alternative to making my code null-safe compatible that avoids these changes?


In null safe Dart, actual optional parameters must either have a default value, or they must be nullable (in which case they have the default default-value of null).

There is no exception. Because of default values, optional parameters are not inherently nullable.

You should not expect existing code to work with null safety as-is. You are expected to do a migration of the code to be null safe.

The easiest way to make your code null safe is to run dart migrate on your project. It will insert most of the necessary ?s for you.

Answered By – lrn

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.