Warm tip: This article is reproduced from stackoverflow.com, please click
dart flutter extension-methods

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

发布于 2020-03-31 22:54:52

Let's say I create two files. In first I create an extension function and call it from class in another file.

File date_extensions.dart:

import 'package:date_format/date_format.dart';

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

and file some_date_class.dart:

import 'date_extensions.dart';

class SomeClassWithDate{

  DateTime dateTime;

  SomeClassWithDate(this.dateTime);

  toString() => dateTime.getSQLFriendly();

}

Now, I get an error:

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();

Now, when I put extension function in the same file where I call it, everything works fine.

Is this a bug, a feature or am I doing something wrong? I would like that the latter is the answer. :)

Questioner
Draško
Viewed
41
Miguel Ruivo 2020-01-31 19:57

Anonymous Dart extensions (those without a name) will be only visible to the file where they are in.

If you want to use it on other files, give it a name.

import 'package:date_format/date_format.dart';

extension MyExtension on DateTime {}

This probably should be added to Dart extensions documentation.