Flutter-Extension Methods

Avnish Nishad
2 min readDec 4, 2021

--

Suppose you’re using some 3rd party library or even a flutter class and you need convert the output as per your need. One way is that we can make a helper function that takes input and convert that in the form we want.

Dart come with another solution to your problem, the Dart team comes up with Extension methods that can be added to the already present classes or even widgets.

extension Ex on num {double numOfPrecision(int n) => double.parse(toStringAsFixed(n));}

🟢Setting-up for extension methods:

Extension methods are introduced in Dart 2.7, So we need to set up the Dart SDK version in pubspec.yaml.

environment:
sdk: ">=2.7.0 <3.0.0"

Without this, Extension methods will not work and will throw errors while running your application.

🟢 Writing Extension Methods

extension Extension on String{
String get addHello=> "Hello, "+this;
}

We can use the above extension to any String like below

String greet="Avnish".addHello;  //output: greet="Hello Avnish"

🟢Can it be used for the flutter widget too? The answer is yes.

extension WidgetExtension on Widget{
Widget horizontalPadding(double padding)=>Padding(
padding:EdgeInsets.symmetric(horizontal: padding),
child:this);
Widget center()=> Center(child:this);
}

Use of the above extension

Text(
'Hello, World!',
style: Theme.of(context).textTheme.headline4,
).center(); //It will center the Widget
//or
Text(
'Hello, World!',
style: Theme.of(context).textTheme.headline4,
).horizontalPadding(10); // will add horizontal padding
// or we can cascade both the methods.
Text(
'Hello, World!',
style: Theme.of(context).textTheme.headline4,
).horizontalPadding(10).center()

🟢Where we can not use extensions methods? We can use extension methods on any DataType and even on var type variables but it will not work with dynamic type variables.

Thank you, Please clap if you find the article helpful. For more information about extension refers to https://dart.dev/guides/language/extension-methods

--

--