Draško
Draško

Reputation: 2221

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

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. :)

Upvotes: 8

Views: 2290

Answers (1)

Miguel Ruivo
Miguel Ruivo

Reputation: 17756

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.

Upvotes: 17

Related Questions