Does Dart have extension methods like c#?
6 years later and extension functions are finally on the horizon: https://github.com/dart-lang/language/issues/41#issuecomment-539251446
They will be included in dart 2.6
Not yet. See issue 9991 - scoped object extensions.
Yes, this was introduced in Dart 2.6
.
The syntax is the following:
extension YourExtension on YourClass {
void yourFunction() {
this.anyMember(); // You can access `anyMember` of `YourClass` using `this`.
anyMember(); // You can access `anyMember` of `YourClass` without `this`.
}
}
void main() {
YourClass yourVariable;
yourVariable.yourFunction(); // valid
}
You can also extend types like int
:
void main() {
5.fancyPrint();
3.minusThree; // returns 0
}
extension FancyInt on int {
void fancyPrint() => print('The magic number is $this.');
int get minusThree => this - 3;
}
You can learn more here.