我可以在Dart中的任何类上使用扩展方法吗?

我可以在Dart中的任何类上使用扩展方法吗?,dart,extension-methods,Dart,Extension Methods,我正在尝试为Decimal类编写一个扩展方法,其中包含: void parse() { Decimal two = Decimal.two; } extension on Decimal { static Decimal get two => Decimal.fromInt(2); } 然而,Dart说“getter'two'不是为类Decimal定义的。”扩展方法是否只对Dart本机类有效 谢谢大家! 在导入时使用以下代码行: import 'YourFileName.dar

我正在尝试为Decimal类编写一个扩展方法,其中包含:

void parse() {
  Decimal two = Decimal.two;
}

extension on Decimal {
  static Decimal get two => Decimal.fromInt(2);
}
然而,Dart说“getter'two'不是为类Decimal定义的。”扩展方法是否只对Dart本机类有效


谢谢大家!

在导入时使用以下代码行:

import 'YourFileName.dart' show ExtensionName;
在“YourFileName.dart”中,应该是这样的:

extension  ExtensionName on Decimal {
  static Decimal get two => Decimal.fromInt(2);
}
然后根据您的要求使用它


请告诉我,如果您仍然在任何地方使用扩展dart

的话,请告诉我正确的方法是不使用关键字
静态
,因为这些方法与
相关

extension ExtensionName on Decimal {
  // `static` keyword removed
  Decimal get two => Decimal.fromInt(2);
  // `this` means the decimal to which this extension method is applied
  Decimal get square => this * this;     
}

这似乎只有在我使用
ExtensionName调用它时才起作用。两个
您必须手动输入导入?如果是这样的话,现在就跳过它们。。。这会浪费更多的时间。不,那就导入你的文件吧。。试试看。