What is difference when you use curly brackets inside constructor in dart classes and when you don’t use it. And why you can not have not nullable and not initialized fields inside constructor when you use curly brackets, but you can when you don’t use curly brackets.
Here is example:
class Animal{
String name;
int age;
Animal({this.name, this.age});
}
When I write class like this, there is error which says: "The parameter ‘name’ can’t have a value of ‘null’ because of its type, but the implicit default value is ‘null’.", and same for ‘age’.
class Animal{
String name;
int age;
Animal(this.name, this.age);
}
But when I don’t use curly brackets there is no error, it allows to have null fields in constructor.
3
Answers
In Dart, braces {} define named parameters, while their omission defines positional parameters. By default, when named parameters are used with curly braces, they are nullable and optional. To enforce non-nullability, use the required keyword before the parameter name. For positional parameters, they are required by default, but can still be nullable if not explicitly initialized.
with braces
so you cant map not nullable value to null because Class Null is not a subtype of String or int or any other class after null safety
When you use braces, you define named parameters. For example:
You should instanciate like this:
If you define your constructor without braces, you defined positionnal parameters.
Then you should instantiate like this:
If you add
required
keyword, you make the parameter mandatory.If you declare a property nullable with a
?
after type, for ewampleyour name parameter become not mandatory.