Dart Extensions Methods
As you all know dart is client optimized programming language for multiple platforms and that special term client optimized always indicates that Dart will always come with more suitable and optimized techniques to make developers work with ease. the same thing happened during the announcement of Dart 2.6 when extensions were introduced however that was for a preview but it was finally released in 2.7. Basically extensions feature is the way to add functionality to existing libraries.
If we understand extension methods by a scenario then it would be like
When you’re using someone else’s API or when you implement a library that’s widely used, it’s often impractical or impossible to change the API. But you might still want to add some functionality.
then the most probable solution for that is by writing wrapper classes with static methods and members and it could cause an increase of the number of objects and then extensions feature come in to play.
Sometimes you might get confused in order to clarify the difference between wrapper and extensions so for your information
In Wrapper classes object is passed explicitly to the static methods while in extensions it is extended implicitly.
So this was basic introduction now let’s clarify a few things about extensions
- How can we use extensions
- where it is suitable to use and where we should refrain from it
Implementation
Before going over implementation of the extension the first thing which you need to pay attention to is the Dart SDK version. This should be ≥ 3.3, inside your pubspec.yaml
environment:sdk: ">=3.3.0 <4.0.0"
The syntax for the actual implementation
extension <extension_name> on <type> {
(<member_definition>)*
}
Example
Let’s understand it by example, suppose if you are getting data from any third-party API and you are getting value in Celsius but need to show it in Farhenheit, what would you do ??
Simple you would convert it like this
Extension Methods
void main() {
double tempCelsius = 20.0;
double tempFarhenheit = tempCelsius* 1.8 + 32;
// celsiusToFarhenheit();
print('${tempCelsius}C = ${tempFarhenheit}F');
}
but what if you need show throughout in your application then you can do this everywhere but there would be a lot of boilerplate code so here extensions come in because you don’t need to call extensions methods by its name
and the implementation will be like
void main() {
double tempCelsius = 20.0;
double tempFarhenheit = tempCelsius.celsiusToFarhenheit();
print('${tempCelsius}C = ${tempFarhenheit}F');
}
extension on double {
double celsiusToFarhenheit() => this * 1.8 + 32;
}
In this example, we have understood three things
- It leverages the type system
- makes our code much easier to understand
- avoids overloading generic numeric types such as
double
, with domain-specific logic for temperature conversion.
Extension Operators
void main() {
List prices = [2, 5, 6.75];
print("\nPrice listing after doubling the value");
print(prices ^ 2);
}
extension<T> on List<T> {
List<num> operator ^(int n) =>
this.map((item) => num.parse("${item}") * n).toList();
}
In this example, you can see how we are doubling the values of the list by using extension methods and the output will be
Price listing after doubling the value [4, 10, 13.5]
That was Dart portion, now let’s understand with Flutter
Suppose you are designing UI of app and there are numerous circular Cards where you need to define its shape everywhere so you need to call that circular property everywhere then again we would write the extension method for this see in the example
import 'package:flutter/material.dart';
import 'package:flutter_route_obser/extension_method.dart';
class PageOne extends StatefulWidget {
@override
_PageOneState createState() => _PageOneState();
}
class _PageOneState extends State<PageOne> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Card(
color: Colors.green,
shape: ShapeBorderX.roundedRectangle(50),
child: Container(
height: 50,
width: 50,
),
),
),
);
}
}
for the extension methods, we make a separate class where all different extensions are described and we only need to call them.in this example, you can see that we are calling shape from the extension method
import 'package:flutter/material.dart';
extension ShapeBorderX on ShapeBorder {
static ShapeBorder roundedRectangle(double radius) {
return RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(radius),
),
);
}
}
extension WidgetPaddingX on Widget {
Widget paddingAll(double padding) => Padding(
padding: EdgeInsets.all(padding),
child: this,
);
}
extension methods are defined by using extension keyword after that we will be able to call all methods without creating any instance variables.
Conclusion
In conclusion, we found that as a developer we have also options to get rid off of a lot of boilerplate and it helps to use the property of any method without creating any instance variables which a big boon when it comes to using any method from different classes.
Thanks for reading this article if you find anything that could be improved please let me know, I would love to improve.💙
If this article has helped you a bit and found interesting please clap!👏
Feel free to connect with us:
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.