sdk
sdk copied to clipboard
Allow opt. class properties to default to their property type if available before null when using [] Inside the constructor parenthesis
So currently you have to define default values to optional properties inside the construct's parenthesis when using [] instead of it implicitly understanding its default value when we're using [] on those said properties. Maybe I'm also understanding the [] incorrectly.
class User {
int id;
String name;
User([this.id = 0, this.name = ""]);
}
Would be nicer to have this functionality:
class User {
int id;
String name;
User([this.id, this.name]);
}
Is there a reason for the explicit default value to be null instead of the property type if it exists before nulling? when using the [] inside the construction parenthesis since it has an explicit understanding behind what those square braces mean.
This tracker is for issues related to:
- Dart core libraries ("dart:async", "dart:io", etc.)
- Dart VM
[] means here that the parameters are positional optional parameters. So the user of your User class can choose to specify zero, one or both of the parameters. This is why we need to provide default values since if the user does not provide a value, the value are going to be defaulted to null which is not allowed for non-nullable types.
If we want to force the user to provide the arguments, you need to use required positional arguments:
class User {
int id;
String name;
User(this.id, this.name);
}
Or required named parameters:
class User {
int id;
String name;
User({required this.id, required this.name});
}
In both cases, we don't need to provide a default value since we are forcing the user of the User class constructor to provide the values and the values must then not be null.
Dart types do not have inherent default values. The default value of the int type is not 0, because there is no default value.
Even if [this.id, this.name] knows that they refer to an int and a String property, there are no default value to choose for those values.
The only default-default value is null, and that only applies to nullable types.
hmm, would dart ever introduce default types for build in types?
Well, it hasn't so far.
It's not impossible, but it's also not providing a big value. It wouldn't allow anything you cannot express today, you just have to do it explicitly by writing = 0 or = "".
It won't apply to generic types, unless having a default value can somehow become a property of a type variable (which means needing a constraint on the type parameter to only allow types with default values as arguments). That's a larger change.