Dart 扩展函数只有在调用它的同一文件中时才可见

Dart extension function visible only if is in the same file where it is called

假设我创建了两个文件。首先,我创建了一个扩展函数并从另一个文件中的 class 调用它。

文件date_extensions.dart:

import 'package:date_format/date_format.dart';

extension on DateTime {
  String getSQLFriendly() => formatDate(this, ["yyyy", "-", "MM", "-", "dd", " ", "HH", ":", "mm", ":", "ss"]);
}

和文件 some_date_class.dart:

import 'date_extensions.dart';

class SomeClassWithDate{

  DateTime dateTime;

  SomeClassWithDate(this.dateTime);

  toString() => dateTime.getSQLFriendly();

}

现在,我得到一个错误:

lib/test/some_date_class.dart:9:26: Error: The method 'getSQLFriendly' isn't defined for the class 'DateTime'.
 - 'DateTime' is from 'dart:core'.
Try correcting the name to the name of an existing method, or defining a method named 'getSQLFriendly'.
  toString() => dateTime.getSQLFriendly();

现在,当我将扩展函数放在调用它的同一个文件中时,一切正常。

这是错误、功能还是我做错了什么?我希望后者是答案。 :)

匿名 Dart 扩展(那些没有名字的)将只对它们所在的文件可见。

如果您想在其他文件上使用它,请为其命名。

import 'package:date_format/date_format.dart';

extension MyExtension on DateTime {}

这可能应该添加到 Dart extensions documentation