-
Notifications
You must be signed in to change notification settings - Fork 214
Allow the default value of a parameter to reference a final variable. #1541
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I'd say no to this, with the same reasoning as for every other feature which works only for "final variables". I'd probably be willing to make exceptions for final variables declared in the same class, or perhaps even the same library, because making that refactoring will immediately break the library you're looking at. It then becomes a class-internal or library-internal implementation detail that something is a final field. So, all in all, it does not appear like this would be viable. For Todo copyWith({
String? body,
bool? completed,
DateTime? dueDate,
bool clearDueDate = false,
}) {
return Todo(
body: body ?? this.body,
completed: completed ?? this.completed,
dueDate: dueDate ?? clearDueDate ? null : this.dueDate,
);
} Not as convenient as other languages, but Dart doesn't have overloading allowing it to run different code depending on whether a parameter was omitted or not. All we have is default values, and if you can't create a sentinel value, there aren't many solutions left. |
I think I leave my hopes at creating immutable values at Record's then 😅 With records, this would work right? typedef Todo = {String body, bool completed, DateTime? dueDate};
Todo todo = (body: 'Code', completed: false, dueDate: DateTime.now());
var newTodo = todo.with(dueDate: null); |
I have absolutely no problem with allowing |
Uh oh!
There was an error while loading. Please reload this page.
A more general feature is suggested here:
#140
However, since there is no progress on this issue, I'm wondering if we could allow only a subset of non-constant values to be used as the default value of a parameter?
For example, could we allow final field and/or final variables to be used as a default value?
An example would be:
At this moment, making a nullable field final is almost like an anti-pattern in Dart.
You can not use the
copyWith
method anymore toset
a field to null in an immutable way.As such a
copyWith
method is generally implemented like this:The only way left to change the dueDate to null is manually copying all the previous values:
The text was updated successfully, but these errors were encountered: