Can't have a value of 'null' because of its type 'int'

I'm new at Dart and I'm taking a course but I don't know if I'm doing something wrong at this particular lesson. I have almost the exact code as my instructor, yet I get an Error instead of a "null" result. This is the code:

import 'package:hello_dart/hello_dart.dart' as hello_dart;

// we can also add exceptions on the parameters using "[]"
//
void main(List<String> arguments) {

  var name = sayHello("Pink", "Unicorn");
  print(name);



}

String sayHello(String name, String lastName, [int age]) => "$name "
    "$lastName $age";




The idea of this lesson is to create exceptions on the function's parameters. On this example, he adds [] on "int age" to add an exception and erases "$age". With that he gets "Pink Unicorn null" as a result.

But I get instead this error:

The parameter 'age' can't have a value of 'null' because of its type 'int', but the implicit default value is 'null'. Try adding either an explicit non-'null' default value or the 'required' modifier. String sayHello(String name, String lastName, [int age]) ^^^

The course is at least four years old, so maybe there was an update where Dart no longer gives a "null" result to an "int" value ? or am I doing something wrong ? https://prnt.sc/cq-YmQgPVx1R

Upvotes: 0

Views: 36

Answers (1)

nvoigt
nvoigt

Reputation: 77285

Yes, this course is outdated, it missed .

Those are optional positional parameters. Please do not call that "exception", since "exception" is a word generally used for something totally unrelated in almost all programming languages including Dart.

Since an int can be longer be null, your optional positional parameter needs to be of type int? to be able to have null as a value.

So this:

void main(List<String> arguments) {
  var name = sayHello("Pink", "Unicorn");
  print(name);
}

String sayHello(String name, String lastName, [int? age]) => "$name "
    "$lastName $age";

Will produce the output:

Pink Unicorn null

For more information on "null safety" and why it's a really great feature, see https://dart.dev/null-safety

Try to use tutorials from the last year at least. Flutter and Dart change fast, to the better, and you should not start learning something only to have outdated knowledge when you are done. Make sure you are learning from a source that is current.

Upvotes: 1

Related Questions