Extension Methods in Flutter

Abhishek Dixit
GYTWorkz
Published in
2 min readJun 21, 2022

In Dart 2.7, Extension methods are introduced as a way to add functionality to existing libraries. You may be using extension methods without even realising it. When you use code completion in an IDE, for example, it suggests extension methods in addition to regular methods.

Requirements

To start, ensure that your Flutter project that uses the extension methods feature using the Dart SDK version. This must be Dart 2.7, the version in which this feature was added. You can verify this within your pubspec.yaml :

environment:sdk: ">=2.7.0 <3.0.0"

Syntax :

extension <extension_name> on <type> {
(<member_definition>)*
}

Let’s take a scenarios where we can use extension methods

Examples :

  1. For converting the String into int datatype
int.parse('10')

You might have used this way to convert the string into integer. Similarly, you can use this way to create an extension method for this standardised way.

To achieve that, we can extend the String Class further to increase its functionality like this,

extension NumberParsing on String { // convert string to int 
int parseInt() {
return int.parse(this);
}
}

Here, we have extended the String Class to convert the String datatype to Integer Datatype

Usage:

print('42'.parseInt()); 

2. For converting the String into int datatype

print(value[0].toUpperCase() + value.substring(1));

we can extend the String Class further to increase its functionality like this,

extension CapitaliseString on String {// Capitalise the first letterString get CamelCase {
return this[0].toUpperCase() + this.substring(1);
}
}

Usage :

print('flutter'.CamelCase()); //output Flutter

Likewise, we can create multiple extension methods to increase the functionality of the existing classes. We can create extension method for any type of class.

Don’t forget to connect with me on:

--

--