DartJS Extension Methods use for writing clean and efficient code in Flutter

Ashish Ramtekkar
2 min readJul 14, 2020

--

Flutter | DartJS | Extension

we’re going to be taking a look at extension methods in dart and how they
can be useful in writing clean and efficient code in dart and how they can
also, be used in writing reusable and customizable widgets in the flutter.

  1. Flutter extension Syntax
  2. Writing custom extension with and without argument
  3. Invoke the custom extension method on any widget

Note : Flutter extension methods is available ≥ 2.7

By the end of this article, you’ll have the knowledge to write your own extensions to use in all your flutter apps and make your code looks more concise and readable.

Well, we use extension type on Widget class, normally syntax look so simple and straight forward

Syntax :extension <name (optional)> on <type> { 
// methods, getters, setters, operators
}
Example:
extension CustomclassName on Widget {

}

Note: Widgets are the central class hierarchy in the Flutter framework. A widget is an immutable description of part of a user interface. Widgets can be inflated into elements, which manage the underlying render tree.

You can write a number of custom methods in the above CustomclassName class.

extension CustomclassName on Widget {//this method with no arugment will wrap the any widget with container
Widget wrapWithContainer() {
return Container(
child: this,
);
}
}

We can add custom properties to the returned widget in the above function with one argument

extension CustomclassName on Widget {Widget wrapWithContainer(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
borderRadius: new BorderRadius.only(
topLeft: const Radius.circular(20.0),
topRight: const Radius.circular(20.0),
),
color: Theme.of(context).backgroundColor,
),
child: this,
);
}
}

How to use a custom extension method on any widget?

import path_to_CustomclassName@override
Widget build(BuildContext context) {
return Scaffold(
body : Text("Text Message").wrapWithContainer(context);
);
}

Simple ? , its really helpful to write the custom shape or widgets using extension and use it in any of the widget in both StatefulWidget && StatelessWidget classes.

Example ://customext.dart
extension
CustomExtension on Widget {
Widget padAll(double padding) = > Padding(
padding: EdgeInsets.all(padding),
child: this
);
}
//main.dart
import path_to_CustomExtension
@override
Widget build(BuildContext context) {
return Scaffold(
body : Column(
children: [
Text("Test").padAll(5),
Text("Message").padAll(5),
Text("Superb ?").padAll(5),
],
)
);
}

--

--