What are Extension Methods and it’s use in Flutter?

Extension functions can be added to classes which are already compiled.

Watch Video Tutorial

class Utils {
static String firstLetterToUpperCase(String string) {
if (null != string) {
return string[0].toUpperCase() + string.substring(1);
}
return null;
}
}
extension ExtendedString on String {
// int
get firstLetterToUpperCase {
if (null != this) {
return this[0].toUpperCase() + this.substring(1);
}
return null;
}
}
Text('hello world'.firstLetterToUpperCase()),

Extend Widgets

Container(
padding: const EdgeInsets.all(16),
margin: const EdgeInsets.all(16),
color: Colors.green,
child: Text(
'Hello World',
style: TextStyle(
fontSize: 50.0,
color: Colors.white,
),
),
),
extension ExtendedText on Text {
//
Container addBox() {
return Container(
padding: const EdgeInsets.all(16),
margin: const EdgeInsets.all(16),
color: Colors.green,
child: this,
);
}
Text setBigWhiteText() {
if (this is Text) {
Text t = this;
return Text(
t.data,
style: TextStyle(
fontSize: 50.0,
color: Colors.white,
),
);
}
return null;
}
}
Text('Hello World').setBigWhiteText().addBox(),
extension ExtendedText on Widget
import 'your_class.dart' show ExtendedText;
import 'your_class.dart' hide ExtendedText;

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vipin Vijayan

Vipin Vijayan

Flutter, React Native, Android, iOS App developer.