extension_declares_instance_field
Extensions can't declare instance fields.
Description
#The analyzer produces this diagnostic when an instance field declaration is found in an extension. It isn't valid to define an instance field because extensions can only add behavior, not state.
Example
#The following code produces this diagnostic because s
is an instance field:
extension E on String {
String s;
}
Common fixes
#If the value can be computed without storing it in a field, then try using a getter or a method:
extension E on String {
String get s => '';
void s(String value) => print(s);
}
If the value must be stored, but is the same for every instance, try using a static field:
extension E on String {
static String s = '';
}
If each instance needs to have its own value stored, then try using a getter and setter pair backed by a static Expando
:
extension E on SomeType {
static final _s = Expando<String>();
String get s => _s[this] ?? '';
set s(String value) => _s[this] = value;
}
Unless stated otherwise, the documentation on this site reflects Dart 3.7.3. Page last updated on 2025-05-08. View source or report an issue.