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 ! :)
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With