Closed
Description
Cannot use record
as default value for optional parameter of class constructor.
Static analysis shows error non_constant_default_value. When I try to start, I get several errors:
- Error: Not a constant expression.
- Error: Constant evaluation error:
Example code (DartPad):
abstract class AnimalNames {
static const dogName = (buddy: 'Buddy');
}
class Dog {
Dog({this.name = AnimalNames.dogName.buddy});
final String name;
}
void main() {}
Functionally similar working code that doesn't use record (DartPad):
abstract class AnimalNames {
static const dogNameBuddy = 'Buddy';
}
class Dog {
Dog({this.name = AnimalNames.dogNameBuddy});
final String name;
}
void main() {}
Dart version used: DartPad stable channel (Based on Flutter 3.13.0 Dart SDK 3.1.0)
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
lrhn commentedon Aug 23, 2023
This is working as intended. The expression
AnimalNames.dogName.buddy
is not a constant expression, because it calls a getter.That getter happens to be the getter of a record field of a constant record. We could safely allow that, because we know the getter is definitely side-effect free and we can evaluate it at compile-time. But we currently do not allow it.
There is already a language request for that: dart-lang/language#3004
so closing this and deferring to the language repo issue.