Language:

Search

the parameter 'key' can't have a value of 'null' because of its type 'key', but the implicit default value is 'null'.

  • Share this:
post-title
post-title

Why does this Error Occur?

This error occurs because non-nullable parameters cannot be null with null safety enabled.

Values may be null in the function and the constructor when the function is called without the named parameter. This is incorrect because the types are non-nullable and must never be null.

How to Solve this Error?

required

This means that a variable is essential.

void sum({required int number}) {
  // ...
}

The number parameter must be given a value at all times.

The default value

If a parameter contains a default value, we can call the function without specifying the parameter value because the default value will be used instead:

void sum({int number = 10}) {
  // ...
}

Now, when we will call sum(), the number parameter will have a value of 10, which is definitely non-null.

Nullable argument

We'll need to null-check the argument before utilizing it in your function.

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

class Fuu extends StatelessWidget {
  const Fuu({Key? key}): super(key: key);
  // ...
}

Positional Parameter

Positional arguments can be declared nullable or non-nullable. However, they cannot be marked with required or have default values because they must always be passed.

void fuu(int p1) {} //is invalid.
void cuu(int? p1) {} //is valid.
Ammar Javed

Ammar Javed

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