The parameter can't have a value of 'null' because of its type in Dart

  • Share this:

This occurs because your non-nullable parameter factor or key cannot be null with null safety enabled.

When the function is called without the named parameter: calculate() or Foo(), these values may be null in the function. This is incorrect code because the types (int and Key) are non-nullable and must never be null.


Three options for dealing with this:



This is the most typical solution to the problem, and it means that a variable must be set. This means that if we have (note the keyword that is required):

void calculate({required int factor}) {
  // ...

We specify that the factor parameter must be given at all times, which addresses the problem because only calculate(factor: 42) et al. are legitimate function calls.

The default value
Providing a default value is another option. If a parameter contains a default value, we can call the function without specifying it because the default value will be used instead:

void calculate({int factor = 42}) {
  // ...

Now, when you use to calculate(), the factor will be 42, which is definitely non-null.


Nullable argument

The third option is one you should really consider, namely, do you want a nullable parameter? If this is the case, you'll need to null-check the argument before utilizing it in your function.

However, because you don't always want to supply a key to your widget in Flutter (notice the nullable Key? type), this is the most frequent approach to handle the Key key issue:

class Foo extends StatelessWidget {
  const Foo({Key? key}): super(key: key);

  // ...

You may now securely build Foo() without having to provide a key.

Positional Parameter
Note that positional arguments can be declared nullable or non-nullable in the same way; however, they cannot be marked with needed or have default values because they must always be given.

void foo(int param1) {} // bar(null) is invalid.

void bar(int? param1) {} // bar(null) is valid.

Ammar Javed

Ammar Javed

Still Learning | Still Searching | Still Exploring | The secret of your success is determined by your daily agenda.