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;
}
除非另有说明,文档之所提及适用于 Dart 3.7.3 版本,本页面最后更新时间: 2025-05-08。 查看文档源码 或者 报告页面问题。