Home > database >  How come positioned parameters pass through the null safety check in Dart?
How come positioned parameters pass through the null safety check in Dart?

Time:05-17

The following lines of code aren't valid in Dart:

void introduce({String name, int age}) {
  print('My name is $name and I am $age years old.');
}

The compiler will complain about the null safety of the parameters.

But if we switch to the positioned parameters, the compiler suddenly stops complaining about the null safety of the parameters, and the following becomes valid:

void introduce(String name, int age) {
  print('My name is $name and I am $age years old.');
}

CodePudding user response:

Positioned parameters are inherently required. Named and positional optional parameters are optionally passed by the caller and it's therefore possible that they're null. One can make the normally optional named parameters required by marking them required.

void introduce({required String name, required int age}) {
  print('My name is $name and I am $age years old.');
}
  • Related