Flutter extension methods and how to use it?

What is Flutter extension methods and how to use it

Before drive into extension methods let’s understand about customization which means to modify something to suit a particular individual or task and flutter extension methods does the same thing.

Now let’s understand Extension methods

The feature named Extension methods, introduced in Dart 2.7. It provides the flexibility to customize existing method or widgets so that we can add new functionality to existing libraries. Although it does not allow us to modify existing code directly, It gives us the ability to customize a class in a way that we can read and use it easily.

We can write an extension for getters, setters and operator as well, these are called extension members

Let’s understand this better by using the instance as an example.

Consider that your app call an api and it returning status as string with value “0” or “1” i.e “0” means false and “1” means true.

String status = “1”;

so if we want to check it directly as boolean inside if condition then we need to check explicitly as below-

if(status == “1”){
  // perform operation
}

Well, this process will be working fine!

But every-time you check status as boolean variable you need to call explicitly and it will be repeated code every-time.

So is there any better option?

Yes, there is a way, you can perform the same operation with a better approach like, think if there can be a method called toBool() which will return true if status is “1” otherwise false and you can call it with variable status like-

if(status.toBool()){
    // any other operation
}

Isn’t it interesting?

So here the concept of extension method comes into existence. We can perform the same operation with extension method.

Now let’s start implementing..

Requirement:

Dart : 2.7 or greater version

Syntax for writing an extension

extension <extension name> on <type> {
	(<member definition>)*
}

file: extension.dart

extension BoolParsing on String {
   bool get toBool() {
     return this.toLowerCase() == “1”;
   }
}

explanation –

With this, we have created our first extension named as BoolParsing on a String class. Inside this, we have written a getter which determines whether an instance of String is “1” or not and it return true if it’s value is “1”.

Now we can call the extension in our app as below-

mport extension.dart
main(){
	String status = “1”;
	if( status.toBool()){
		// status is true
	}else{
		// status is false 
	}
}

Writing extended method with parameter

extension ExtendedString on String {
String withSuffix(String suffix) {
  return '$suffix $this';
 }
}

main() {
   print('C++'.withSuffix('is a language'));
}

Output: C++ is a language

Writing extended method with an operator

extension ExtendedString on String {
 String operator &(String suffix) => '$suffix $this';
}

main() {
     print('C++'&'is a language');
}

Output: C++ is a language

Biggest advantage of Flutter Extension

How can we use the extension methods for widgets as well? Let’s see..

Suppose we want to center a widget or give padding to widgets. Then normally we will wrap widget with the Center widget for centering the widget and Padding for padding like this-

Container(
  child: Column(
    children: [
      Center(Text("I am a center text")),

      Padding(
        padding: const EdgeInsets.only(top:20),
        child: Container(
          height: 20,width:50,color:Colors.green
          chilld: Text("Padded text"),
        ),
      )
    ],
    
  )
)

But now if we implement extended method for center and paddingTop the code will be look like below and you use anywhere with any widgets in your app

Extended Methods-

extension ExtendedWidget on Widget {
  center() {
    return Center(
      child: this,
    );
  }

  paddingTop(double top) {
    return Padding(
      padding: EdgeInsets.only(top: top),
      child: this,
    );
  }
}

Using Extended Methods-

Container(
  child: Column(
    children: [
      Text("I am a center text").center(), // called center() extension to Center the Text Widget
      Container(
          height: 20,width:50,color:Colors.green
          chilld: Text("Padded text"),
      ).paddingTop(top:20), // called paddingTop() extension with argument
      
    ],
    
  )
)

explanation –

Here instead of wrapping Text widget with Center, we are calling center() extension after text widget as Text().center(). Similarly for padding top.

So You can clearly see that how nested code is reduced and you can increase the readability of the code. Additionally you will get autocomplete suggestions in your favourite code editor for the extensions.

read official documentation

You can get the full code below-

Thanks for reading..

You may also like...

Leave a Reply

Your email address will not be published.