Johnny
Johnny

Reputation: 355

Import extension method from another file in Dart

With Dart 2.6, I can use extension methods like this :

extension on int {
  int giveMeFive() {
    return 5;
  }
}


main(List<String> arguments) async {
  int x;
  x.giveMeFive();
}

Everything works perfectly ! :D

But now if I want to put my extension method in another file like this :

main.dart

import 'package:untitled5/Classes/ExtendInt.dart';

main(List<String> arguments) async {
  int x;
  x.giveMeFive();
}

ExtendInt.dart

extension on int {
  int giveMeFive() {return 5;}
}

It fails with a depressing error ..

bin/main.dart:9:5: Error: The method 'giveMeFive' isn't defined for the class 'int'.
Try correcting the name to the name of an existing method, or defining a method named 'giveMeFive'.
  x.giveMeFive();
    ^^^^^^^^^^

Is it not allowed to do that or am I doing something wrong ? Thanks for reading ! :)

Upvotes: 29

Views: 8120

Answers (1)

Erik Ernst
Erik Ernst

Reputation: 1054

This is working as intended. An extension with no name is implicitly given a fresh name, but it is private. So if you want to use an extension outside the library where it is declared you need to give it a name.

This is also helpful for users, because they may need to use its name in order to be able to resolve conflicts and explicitly ask for the extension method giveMeFive from your extension when there are multiple extensions offering a giveMeFive on the given receiver type.

So you need to do something like

extension MyExtension on int {
  int giveMeFive() => 5;
}

Upvotes: 44

Related Questions