0

The code below fails when compiling with Null Safety the following error:

The parameter namedParam can't have a value of null because of its type, and no non-null default value is provided.

void main() {
  Foo(callbackWithNamedParam: ({namedParam}) { 
    print('param=$namedParam');
  }).callback();
}

class Foo {
  final void Function({required int namedParam}) callbackWithNamedParam;
  
  Foo({required this.callbackWithNamedParam});
  
  void callback() {
    callbackWithNamedParam(namedParam: 10);
  }
}

When compiling without Null Safety the code compiles perfectly well.

DartPad with Null Safety that fails compiling

DartPad without Null Safety that compiles well

Is there a way to fix it:

  1. Without switching to positional parameter
    AND
  2. Without making the named parameter nullable?
tonymontana
  • 5,728
  • 4
  • 34
  • 53

2 Answers2

2

Make your named param int?. It will then accept either an int or null:

final void Function({int? namedParam}) callbackWithNamedParam;
Randal Schwartz
  • 39,428
  • 4
  • 43
  • 70
  • Thanks, it works with nullable named parameter but I don't want to make it nullable. I clarified the question. – tonymontana Jan 23 '21 at 22:40
  • Well. I totally missed it. I need to add `required` to the anonymous function as well. Thank you for making me recheck my code. – tonymontana Jan 23 '21 at 22:46
  • Can you please clarify both cases (nullable and non-nullable) parameters for the sake of completeness of the answer for other developers to come? Thanks. – tonymontana Jan 23 '21 at 22:56
1

Adding on Randal's answer. From Dart's documentation

enter image description here

So in order to resolve my issue, I had to add required to the anonymous function

Foo(callbackWithNamedParam: ({required namedParam}) { 
                              ^^^^^^^^
    print('param=$namedParam');
  }).callback();

My working code can be found in this Dartpad

tonymontana
  • 5,728
  • 4
  • 34
  • 53