Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create extension method in Dart

Tags:

flutter

dart

Normally When I create a custom class I can create a function that uses that class as a parameter for example:

class Sphere{
    double calculateRadius() {return 40.0;}
}

So I can then call Sphere.calculateRadius().

But with pre-existing classes like for example the String one, this can't be done. For Example. I've tried doing something like:

String.createFrom(String s){return "new";}

but it doesn't work (Android Studio doesn't even make me compile.).

Is this possible, and if it is, how could I do it in Dart? And If I created it, how would I access the object I called the method from? (the String in the example)

like image 927
Fabrizio Avatar asked Feb 25 '19 21:02

Fabrizio


People also ask

How do you make a dart extension?

To create a local extension that's visible only in the library where it's declared, either omit the extension name or give it a name that starts with an underscore ( _ ). The members of the extension can be methods, getters, setters, operators. Extensions can also have static fields and static helper methods.

What are the extension methods in DART?

Extension methods are new as of Dart 2.7. They allow you to add functionality to existing libraries and classes. For example, you can add extra functionality to the Dart core String library, that are only available in your app.

What is extension method function?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

How do you extend a list in flutter?

If you wrap/delegate an existing list you should use the last option. Otherwise, use one of the two first options depending on your type hierarchy (mixin allowing to extend another Object). You can also use DelegatingList from package:collection/wrappers. dart in a similar way to the one from quiver.


2 Answers

As of now January 2020, Dart 2.7 officially introduced extension methods. To extend a class, this can be done:

extension NewExtension on double {
  int get myMethod {
    return (1/this*10).toInt();
  }
}
like image 103
Fabrizio Avatar answered Oct 10 '22 20:10

Fabrizio


You probably mean extension methods. That's not yet supported but the Dart team made attempts already to design such a feature and the chances are good it will be added to the language

https://github.com/dart-lang/language/issues/41

like image 21
Günter Zöchbauer Avatar answered Oct 10 '22 18:10

Günter Zöchbauer