在扩展类中找不到扩展方法

时间:2020-08-05 14:03:38

标签: dart

我有这个简单的代码,我想在Test Class中使用扩展方法。

尽管我没有遇到任何代码错误,但是却遇到了编译错误。

我在https://dartpad.dartlang.org/上运行它,但遇到以下错误:

Error compiling to JavaScript: main.dart:7:21: Error: Method not found: 'isTrue'. bool isItThough = isTrue(); ^^^^^^ Error: Compilation failed.

void main() {
   //print(Test().isTrue);
  print(Test().isItThough);
}

class Test {
  bool isItThough = isTrue();
}

extension on Test {
  bool isTrue() => true;
}

1 个答案:

答案 0 :(得分:2)

如果您尝试将此代码粘贴到DartPad中而不是IDE中,则可能会显示警告

The instance member 'isTrue' can't be accessed in an initializer. 

因此,您可以选择像这样修改代码

class Test {
  bool get isItThough => isTrue();
}