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

I know there many answers to this question but I feel like I'm missing something that the other answers can't answer. I'm teaching myself Dart through their website. One of the examples they have is the following

String say(String from, String msg, [String? device]) {
  var result = '$from says $msg';
  if (device != null) {
    result = '$result with a $device';
  }
  return result;
}
Here’s an example of calling this function without the optional parameter:

assert(say('Bob', 'Howdy') == 'Bob says Howdy');
And here’s an example of calling this function with the third parameter:

assert(say('Bob', 'Howdy', 'smoke signal') ==
    'Bob says Howdy with a smoke signal');

I'm trying out something similar in Dartpad

void main() {
 print(testFunction('James', 'end', 'of it all'));
}

String testFunction(String start, String end, [String insert]){
  var result = '$start and this is the $end';
  if(insert != null) {
     result = '$result testing stuff $insert';
  }
  return result;
}

This ends up in the following error The parameter 'insert' can't have a value of 'null' because of its type 'String', but the implicit default value is 'null'.

I'm struggling to understand why that error is popping up considering I've added the third parameter in testFunction. Making the insert parameter optional solves the problem but why is it working for the Dart example and not my test?



Solution 1:[1]

You're missing [String? insert] in the function arguments. The Dart example has this as well in [String? device].

Conceptually, the square brackets indicate that the parameter is optional, but "?" is still needed to indicate that the variable can be a null value

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ad2969