Reputation: 216
class Product {
Product(this.name);
final String name;
}
class Product {
Product({this.name});
final String name;
}
Upvotes: 1
Views: 63
Reputation: 5133
The { }
in the constructor
are used to make the constructor arguments optional.
class Product {
Product(this.name);
final String name;
}
In the above code notice, there are no { }
around arguments in constructor hence while creating a new object using the Product
class it's mandatory to provide name
class Product {
Product({this.name});
final String name;
}
While in the above code the name
argument is optional as it has { }
around it. So while creating an object using this class you can skip the name
parameter.
Upvotes: 0
Reputation: 657376
In the first example the parameter is mandatory positional (you still can pass null
though).
You can call it like:
new Product('Fred')
In the 2nd example the parameter is an optional named parameter.
You can call it like:
new Product()
new Product(name: 'Fred')
Another variant would be an optional positional parameter
class Product {
Product([this.name]);
final String name;
}
You can call it like:
new Product()
new Product('Fred')
Optional parameter always need to be declared after mandatory parameters.
Optional named and optional positional can not be combined.
Upvotes: 1