Flutter

Boost the code with Dart Extensions

By April 27, 2020 February 10th, 2021 No Comments

What is an extension function?

Imagine we need a method for all our Strings in our App. A method called “removeBs” that will remove all “b” from the given String.

One option, it is to create a class Bextractor with a static method. Or just set this static method in a Utils file…

class Bextractor {
  static fun removeBs(String text)=> text.replace('b','');
}

But wouldn’t be great to just call text.removeBs() ?

This is what Extensions are about.

Extension functions is a mechanism to provide new functionality to a class withoit having to modify the class itself.

How to use it?

extension StringRemoveBs on String{
  String removeBs() => this.replaceAll('b', '');
}

Now removeBs method is available like any other method from String class.

You can call “Text example”.removeBs()

Remember a function is an Object in Dart. That means we can apply an extension to any Function! let’s see it!

extension DelayedFunction on Function{
  delayedCall({duration = const Duration(seconds: 1)}){
    Future.delayed(duration).then((value) => this.call());
  }
}

And use it like this:

"A random static string".removeBs.delayedCall(duration:Duration(seconds: 4));

Of course this is useless 🙂 but it shows the flexibility on using Extensions.

Ernie

Author Ernie

More posts by Ernie