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. :)
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.
Yeah, I guess that should be added. :D
It is mentioned on that page ("To create a local extension that’s visible only in the library where it’s declared, either omit the extension name or give it a name that starts with an underscore (_)."), but I do think it's a little hard to find if you're not looking for it.