Dart 在扩展类中找不到扩展方法
我有一个简单的代码,我想在测试类中使用扩展方法 虽然我没有得到任何代码错误,但我得到了一个编译错误 我在上运行此操作,但出现以下错误: 编译为JavaScript:main.dart:7:21时出错:找不到方法:“isTrue”。bool isithough=isTrue();^^^^错误:编译失败。Dart 在扩展类中找不到扩展方法,dart,Dart,我有一个简单的代码,我想在测试类中使用扩展方法 虽然我没有得到任何代码错误,但我得到了一个编译错误 我在上运行此操作,但出现以下错误: 编译为JavaScript:main.dart:7:21时出错:找不到方法:“isTrue”。bool isithough=isTrue();^^^^错误:编译失败。 void main() { //print(Test().isTrue); print(Test().isItThough); } class Test { bool isItTh
void main() {
//print(Test().isTrue);
print(Test().isItThough);
}
class Test {
bool isItThough = isTrue();
}
extension on Test {
bool isTrue() => true;
}
如果您尝试将此代码粘贴到IDE中而不是DartPad中,则可能会看到警告
The instance member 'isTrue' can't be accessed in an initializer.
因此,作为选项,您可以这样修改代码
class Test {
bool get isItThough => isTrue();
}
如果您尝试将此代码粘贴到IDE中而不是DartPad中,则可能会看到警告
The instance member 'isTrue' can't be accessed in an initializer.
因此,作为选项,您可以这样修改代码
class Test {
bool get isItThough => isTrue();
}
对的扩展方法在类型上的
实例上调用,字段初始值设定项在静态上下文中运行,其中不存在此
实例。正确。扩展方法在
类型上的实例上调用,字段初始值设定项在没有此
实例的静态上下文中运行。