Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import extension method from another file in Dart

Tags:

flutter

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

like image 280
Johnny Avatar asked Nov 28 '19 15:11

Johnny


People also ask

How do you use a function from another DART file in Flutter?

Dart has inbuilt support for optionally adding functions to a class when we want to reduce duplicated code but avoid extending the whole class (Source). The mixin keyword enables this by mixing a class with some specific logic. We can restrict the mixin to a specific subclass with on if needed.

What are the extension methods in Dart why to use it?

Extension methods, introduced in Dart 2.7, are a way to add functionality to existing libraries. You might use extension methods without even knowing it. For example, when you use code completion in an IDE, it suggests extension methods alongside regular methods.


Video Answer


1 Answers

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;
}
like image 112
Erik Ernst Avatar answered Sep 18 '22 14:09

Erik Ernst