Dart Extensions Tutorial: Enhance your Flutter Code

You would possibly have already got turn into aware of primary Flutter and Dart data. You would possibly even have your first app already revealed. But there may be all the time room for enchancment. Dart Extensions will help make your code smoother and simplify some code utilization.

This tutorial gained’t educate you methods to make a full Flutter app; the bottom is already finished. Your job might be to refactor an already working CatFoodCalculator app with extensions. You’ll discover all their usages, together with:

  • Fundamental extension creation.
  • Extra superior usages, together with extensions on enums, generics or nullable sorts.
  • Recommendation on when to make use of them and when to not.
Be aware: This Dart extensions tutorial assumes the fundamentals of Dart and Flutter improvement. In case you’re new to Flutter improvement, take a look at Getting Began With Flutter information first.

Getting Began

Obtain the starter challenge by clicking the Obtain Supplies button on the high or backside of the tutorial.

Unzip the downloaded file and open the starter challenge situated in /starter inside your favourite IDE. You may run the challenge on each cellular units and net browsers.

The CatFoodCalculator app is already working. You’ll solely refactor it to incorporate extensions usages.

Take a look at the recordsdata in lib.

The content of the lib folder

First, open lib/information/meal_data.dart. It is a information class holding your cat’s meal information.

Proceed with lib/widgets/counter.dart. It is a UI widget used to extend a counter with buttons as a substitute of getting to kind the brand new worth.

Then, open lib/widgets/meal_info.dart. This widget is a type to kind the beneficial quantity of meals for a cat of a given weight. Be aware that it additionally holds the MealType enum.

Subsequent, have a look at the widgets in lib/widgets/meal_repartition_result.dart. The MealRepartitionResult widget exhibits the ensuing repartition based mostly on MealData.

Lastly, open lib/principal.dart. This comprises the core of your app.

Particularly, search for MyHomePage and its state _MyHomePageState. The non-public technique _mainColumnContent() returns the principle elements of your UI. The strategies _calculateRation() and _updateCatComment() include the enterprise guidelines.

Construct and run the challenge. It is best to see a device to calculate how a lot moist and dry meals your cats want.

The initial state of the CatFoodCalculator app

Play with the values utilizing the textual content fields or the + and buttons. See how the meals repartition modifications because of this.

What Is an Extension Methodology?

On this part, you’ll see what an extension technique is and why it’s helpful.


Creating an extension on a category permits you to add strategies to it with out altering that class. Extensions are helpful for including options to courses you possibly can’t or don’t wish to change.

You may also use them to create shortcuts.

Comparability with Options

When you possibly can’t change a category however wish to add a characteristic associated to it, you’ve got three choices:

  1. Use a worldwide or a static technique
  2. Use a wrapper across the desired class and create the tactic in that wrapper
  3. Use an extension technique

See every of them within the examples beneath:

// 1. Static technique
class StaticMethods {
  static String addCat(String baseString){
    return '$baseString 🐱';

// 2. Wrapper
class WrappedString {
  remaining String baseString;


  String addCat() {
    return '$baseString 🐱';

// 3. Extension
extension Extension on String {
  String addCat(){
    return '$this 🐱';

When beginning with the identical enter String, all three strategies add a ' 🐱' on the finish of the enter. The primary distinction is the way you invoke them.

// 1. Static technique
StaticMethods.addCat('bonjour'); // 'bonjour 🐱'

// 2. Wrapper
WrappedString('bonjour').addCat(); // 'bonjour 🐱'

// 3. Extension
'bonjour'.addCat(); // 'bonjour 🐱'

The extension technique provides a extra fluid API. It feels prefer it’s a basic technique from the bottom class.

Creating and Utilizing a Fundamental Extension

Now that what Dart extensions are, it’s time to study extra about their syntax. You’ll quickly begin including them to the pattern challenge.


Take a look at the instance beneath of a category and its extension.

class ClassToExtend {
  const ClassToExtend({
    required this.aNumber, 
    required this.aString,
  remaining int aNumber;
  remaining String aString;

extension ExtensionName on ClassToExtend {
  String helloWorld() {
    return '$runtimeType says whats up to the world';

  String get whats up => 'whats up $aString';

  int operator +(int different) => aNumber + different;

An extension has a reputation and extends a particular class. Within the instance above, the identify is ExtensionName and the prolonged class is ClassToExtend.

Within the extension physique, you possibly can write new strategies, getters and even operators! You may seek advice from public members of the prolonged class. Within the instance above, you entry aString and aNumber. You may’t entry non-public members of the prolonged class within the extension code.

remaining extendedClass = ClassToExtend(aNumber: 12, aString: 'there');

extendedClass.helloWorld(); // ClassToExtend says whats up to the world
extendedClass.whats up; // whats up there
extendedClass + 8; // 20

You create an object of the prolonged class utilizing a traditional constructor. Then, you invoke the strategies and the operators outlined within the extension as in the event that they have been outlined within the unique class.

Creating StringCaseConverter Extension

On your first extension within the CatFoodCalculator app, you’ll add the firstLetterUppercase() technique to String. Identify that extension StringCaseConverter.

Begin by creating the folder lib/utils. This folder will include all of the extensions you’ll create throughout this tutorial. Then, create the file string_case_converter.dart in it.

You’re now able to create the extension StringCaseConverter. It ought to include the firstLetterUppercase() technique, which, when invoked on a String object, returns its capitalized model. In case you’d like, attempt to do it your self first. :]

Click on the Reveal button to get this extension’s code.

[spoiler title=”Solution”]
Right here’s the answer:

extension StringCaseConverter on String {
  String firstLetterUppercase() {
    remaining firstLetter = substring(0, 1);
    remaining relaxation = substring(1, size);
    return firstLetter.toUpperCase() + relaxation;


With this, you possibly can convert the primary letter of a String to uppercase with out touching the remainder of the String.

Open lib/widgets/meal_info.dart and find the _title() technique. It returns a Textual content widget that shows “WET meals” or “DRY meals” based mostly on the MealType. The road beneath transforms the identify of the MealType enum to uppercase.

remaining foodType = widget.mealType.identify.toUpperCase();

You’ll change this line to remodel the identify of the MealType enum to make solely the primary letter uppercase.

Begin by importing StringCaseConverter:

import '../utils/string_case_converter.dart';

Now, substitute the foodType task with the next:

remaining foodType = widget.mealType.identify.firstLetterUppercase();

Solely the primary letter might be uppercase now.

Sizzling reload and see the up to date title:

Updated Wet and Dry titles

Be aware the cat’s weight remark that seems when you set it to a worth greater than 7.

Superior Usages

Dart extensions can go means past easy String transformations. You may lengthen nullable sorts and generics and might even create non-public extensions.

Nullable Varieties

The cat’s weight feedback don’t begin with an uppercase. You’ll appropriate it utilizing a barely modified model of StringCaseConverter.

Take a look at the _catWeightCommentBuilder() technique in lib/principal.dart.

In case you’d like to make use of firstLetterUppercase() on _catWeightComment, you’d should take care of the truth that the _catWeightComment variable is nullable.

It may appear like this:


Be aware the ? to deal with nullable values.

However there’s a good simpler method: You may make extensions on nullable sorts.

Change StringCaseConverter in lib/utils/string_case_converter.dart with this code:

extension StringCaseConverter on String? {
  String firstLetterUppercase() {
    if (this == null || this!.isEmpty) {
      return '';
    } else {
      remaining firstLetter = this!.substring(0, 1);
      remaining relaxation = this!.substring(1, this!.size);
      return firstLetter.toUpperCase() + relaxation;

Since you deal with the nullable values in firstLetterUppercase(), you don’t want the ? in your technique calls anymore.

Return to lib/principal.dart and alter _catWeightCommentBuilder() to make use of the up to date extension:

Widget _catWeightCommentBuilder() {
  return Textual content(
    textAlign: TextAlign.middle,
    type: Theme.of(context).textTheme.bodyMedium?.copyWith(
          fontStyle: FontStyle.italic,

Don’t overlook to import the extension.

import '../utils/string_case_converter.dart';

_catWeightComment will now begin with an uppercase.

Sizzling reload to see that small change.

The comment text is updated by using Dart extensions on a nullable type


Like common courses and strategies, you possibly can create Dart extensions on generic sorts. You’ll make one to insert a component between every unique checklist aspect.

Add a separator between each element of a list

Within the image above, the unique checklist comprises numbers you want to separate by a comma. That is what you wish to obtain along with your extension.

To do that on a generic Listing, make an extension on Listing<T>, the place “T” is the kind of the weather within the checklist.

First, create a file named separated_list.dart in lib/utils/, then paste the next code in it:

extension SeparatedList<T> on Listing<T> {
  Listing<T> separated(T separator) {
    remaining newList = <T>[];
    for (var i = 0; i < size; i++) {
      if (i == 0) {
      } else {
    return newList;

The separated() technique provides a separator between every aspect of the unique Listing. Be aware that each the Listing and the brand new aspect ought to be of kind T.

This is an instance of methods to use it:

remaining myExampleList = <String>['Sam', 'John', 'Maya'];
print(myExampleList.separated(', ').be part of()); // Prints "Sam, John, Maya"

The ListView widget has a separated constructor like this.

Now you can obtain one thing resembling it with Column and Row.

In lib/principal.dart, find the _mainColumnContent() technique. It returns the kids of the principle Column of your widget tree. Be aware the house variable on the technique’s starting.

const house = SizedBox(peak: 20);

It is used so as to add house amongst all the kids of the Column widget, which is the app’s principal construction. Delete that variable and all of the strains the place it seems.

Now, you want to use the brand new extension. Find the remark TODO Add separation between objects with an extension and substitute the whole line with the code beneath.

].separated(const SizedBox(peak: 20));

With this code, you invoke separated() on the widget checklist earlier than returning it. The extension technique inserts the SizedBox between every unique objects.

Once more, remember to import the extension.

import '../utils/separated_list.dart';

You may as well make an extension technique instantly on Listing<Widget> somewhat than on a generic Listing. Paste the next code on the finish of lib/utils/separated_list.dart:

extension SpacedWidgets on Listing<Widget> {
  // 1. 
  // double defaultHorizontalSpace = 8;

  // 2.
  static const double _defaultHorizontalSpace = 8;
  static const double _defaultVerticalSpace = 8;

  // 3.
  Listing<Widget> _spaced(
      {required double horizontalSpace, required double verticalSpace}) {
    // 4.
    return separated(SizedBox(width: horizontalSpace, peak: verticalSpace));

  Listing<Widget> horizontallySpaced({
    double horizontalSpace = _defaultHorizontalSpace,
  }) {
    return _spaced(horizontalSpace: horizontalSpace, verticalSpace: 0);

  Listing<Widget> verticallySpaced({
    double verticalSpace = _defaultVerticalSpace,
  }) {
    return _spaced(horizontalSpace: 0, verticalSpace: verticalSpace);

Within the code above, you create an extension on a listing of widgets. The extension defines a few strategies that add house among the many widgets within the checklist.

Some essential limitations and options of Dart extensions are highlighted within the code:

  1. Declaring occasion fields is not allowed.
  2. Implementing static fields is allowed.
  3. You may create non-public strategies inside an extension.
  4. It is doable to reuse different extensions in an extension, like SeparatedList is utilized in SpacedWidgets.

Keep in mind to import the lacking references.

import 'package deal:flutter/widgets.dart';

Because of SpacedWidgets, now you can return to lib/principal.dart and substitute your earlier separated() name with the brand new extension.

// Change
].separated(const SizedBox(peak: 20));

// with
].verticallySpaced(verticalSpace: 20);

You are now utilizing SpacedWidgets as a substitute of SeparatedList.

Personal Dart Extensions

Like courses, you may make extensions non-public by beginning their identify with an _.

To make SpacedWidgets non-public, transfer it from lib/utils/separated_list.dart to principal.dart since you’ll use it solely there, and rename it to _SpacedWidgets:

extension _SpacedWidgets on Listing<Widget>{
  // ...

As a result of it begins with an underscore, it is now non-public; you possibly can solely use it within the principal.dart file.

You may as well make extensions non-public by omitting their identify:

extension on Listing<Widget>{
  // ...

Nonetheless, naming an extension make it simpler to know what it does. Furthermore, it provides you a better solution to handle conflicts, as you will see later.

Though it’d sound good to make non-public extensions, it is best to establish the place you possibly can reuse them in your code and alter them to be public. Extensions are useful as a result of they make code extremely reusable.

Static Capabilities, Constructors and Factories

Dart extensions aren’t but excellent. They cannot:

  • Create new constructors
  • Create factories

You may declare static features like within the following instance:

extension StringPrinter on String {
  // 1.
  // static String print() {
  //   print(this);
  // }

  // 2.
  static String helloWorld() {
    return 'Good day world';

This is a breakdown of the code snippet above:

  1. You may’t use this in a static technique. That is as a result of it is static: You make the decision on the category, not on an occasion of the category.
  2. You may outline a daily static technique.
    However its utilization would possibly disappoint you:

// Would not work
// String.helloWorld();

// Would not work
// 'one thing'.helloWorld();

// Works!

You may’t use String to name helloWorld(). You must use StringPrinter instantly, which is not supreme. Having the ability to name String.helloWorld() was the preliminary intention, in spite of everything.

For the CatFoodCalculator app, you may need preferred to return a Slider with a theme included in its constructor as a substitute of getting to wrap the Slider with a SliderTheme.

Copy the next code and paste it in a brand new file lib/utils/themed_slider.dart:

import 'package deal:flutter/materials.dart';

extension ThemedSlider on Slider {
  static Widget withTheme({
    Key? key,
    required double worth,
    required Operate(double) onChanged,
    Operate(double)? onChangeStart,
    Operate(double)? onChangeEnd,
    double min = 0.0,
    double max = 1.0,
    int? divisions,
    String? label,
    Coloration? activeColor,
    Coloration? inactiveColor,
    Coloration? thumbColor,
    MouseCursor? mouseCursor,
    String Operate(double)? semanticFormatterCallback,
    FocusNode? focusNode,
    bool autofocus = false,
    required SliderThemeData themeData,
  }) {
    return SliderTheme(
      information: themeData,
      youngster: Slider(
        key: key,
        worth: worth,
        onChanged: onChanged,
        onChangeStart: onChangeStart,
        onChangeEnd: onChangeEnd,
        min: min,
        max: max,
        divisions: divisions,
        label: label,
        activeColor: activeColor,
        inactiveColor: inactiveColor,
        thumbColor: thumbColor,
        mouseCursor: mouseCursor,
        semanticFormatterCallback: semanticFormatterCallback,
        focusNode: focusNode,
        autofocus: autofocus,

The extension wraps the Slider with a SliderTheme as a substitute of getting to take care of it instantly.

Now, in lib/principal.dart, import the brand new file with:

import '../utils/themed_slider.dart';

Then, find SliderTheme, proper beneath the // TODO Change SliderTheme with ThemedSlider remark. Change SliderTheme, the kid of the Expanded widget, with a name to the brand new extension as within the code beneath:

youngster: ThemedSlider.withTheme(
  worth: _mealRepartition,
  min: 0,
  max: _nbMeals.toDouble(),
  divisions: _nbMeals,
  onChanged: (newVal) {
    setState(() {
      _mealRepartition = newVal;
  themeData: const SliderThemeData(
    trackHeight: 16,
    tickMarkShape: RoundSliderTickMarkShape(tickMarkRadius: 6),
    thumbShape: RoundSliderThumbShape(enabledThumbRadius: 16),
    thumbColor: Coloration(0xffffa938),

You must name ThemedSlider.withTheme() as a substitute of Slider.withTheme(). This limitation is actively mentioned in a GitHub challenge.

Dart Extensions on Enums

Apart from courses, you can even create extensions on enum.

Open lib/widgets/meal_info.dart and be aware the MealType enum declaration on the high of the file.

The quantity of meals it is best to feed to your cat is dependent upon the particular meals, and the package deal often exhibits the beneficial every day consumption. One won’t know the place to seek out the proper data to kind on this type. That is why there is a Assist button, which shows a popup:

The popups giving more information on how much food a cat should eat

The popup content material modifications based mostly on the MealType. In your subsequent extension, you will create a technique to point out this popup.

Add an extension MealTypeDialog in a brand new file, lib/utils/meal_type_dialog.dart:

import 'package deal:flutter/materials.dart';

import '../widgets/meal_info.dart';

extension MealTypeDialog on MealType {
  Future<void> infoPopup(BuildContext context) {
    remaining textual content = this == MealType.moist
        ? 'Yow will discover this information printed on the pack of moist meals'
        : 'Your bag of dry meals ought to have this information printed on it';
    return showDialog<void>(
        context: context,
        builder: (context) {
          return AlertDialog(
            content material: Textual content(textual content),
            actions: [
                onPressed: () {
                child: const Text('OK'),

This extension shows the identical dialog you get if you use the onInfoPressed() technique from _MealInfoState. It exhibits a special textual content based mostly on the MealType.

In meal_info.dart, import the file with the brand new extension:

import '../utils/meal_type_dialog.dart';

Then, search for the // TODO Change onInfoPressed with an extension remark and substitute the onPressed with a name to the MealTypeDialog extension.

onPressed: () => widget.mealType.infoPopup(context),

The infoPopup() technique now takes care of displaying the dialog. You do not want onInfoPressed() anymore, so you possibly can delete it.

And voilà! Because of your extension, you are now displaying a popup instantly by calling a technique on an enum.

Dealing with Conflicts

The CatFoodCalculator app is kind of easy: There is not any API name nor native storage. If you would like to implement it, changing your objects to JSON is an effective place to begin. A method of doing it’s to make use of jsonEncode().

Create an extension JsonConverter in a brand new file, lib/utils/json_converter.dart:

import 'dart:convert';

extension JsonConverter on dynamic {
// ...

You will want dart:convert since you’ll use jsonEncode(). Be aware that the extension is dynamic: It is out there to all kinds, together with your goal class MealData.

Now, add a brand new technique to this extension:

String stringify() {
  return jsonEncode(this);

As you possibly can see, jsonEncode() does the whole job.

In principal.dart, discover the // TODO add a save button right here remark and substitute it with a Save button as within the code beneath.

Listing<Widget> _mainColumnContent() {
  return [
      onPressed: _saveMealData,
      child: const Text('SAVE'),
  ].verticallySpaced(verticalSpace: 20);

You will use this button to simulate saving MealData in _saveMealData(). Create a brand new technique within the _MyHomePageState widget:

void _saveMealData() {
  remaining mealData = MealData.dry(
    nbMeals: _mealRepartition.spherical(),
    eachAmount: _calculateRation(MealType.dry),

  print('Json : ${mealData.stringify()}');

Import JsonConverter extension:

import 'utils/json_converter.dart';

As a substitute of saving MealData someplace, you will solely print it to the console on this instance, due to print(). That is what it is best to learn within the console:

   "nbMeals": 3,
   "mealType": "dry",
   "eachAmount": 122

Another stringify technique may embrace the kind of the item because the preliminary key:

      "nbMeals": 3,
      "mealType": "dry",
      "eachAmount": 122

Return to json_converter.dart and create one other extension:

extension JsonConverterAlt on dynamic {
  String stringify() {
    return '{$runtimeType: ${jsonEncode(this)}}';

This one consists of the runtimeType as the primary key.

Each JsonConverter and JsonConverterAlt have a technique named stringify(). In an actual app, this would possibly occur resulting from utilizing an exterior library.

Return to principal.dart and be aware the error on stringify():

Be aware: A member named ‘stringify’ is outlined in extension ‘JsonConverter’ and extension ‘JsonConverterAlt’, and none is extra particular.

One solution to remedy it’s to make use of the disguise characteristic within the import:

import 'utils/json_converter.dart' disguise JsonConverterAlt;

The error disappears, however you possibly can’t use each extensions on principal.dart with this technique.

One other solution to remedy this drawback is to make use of the names of your extensions: That is why it is best to identify them. Take away the disguise JsonConverterAlt code you added to the import assertion and substitute the physique of the _saveMealData() technique with the next:

remaining mealData = MealData.dry(
  nbMeals: _mealRepartition.spherical(),
  eachAmount: _calculateRation(MealType.dry),

print('Json v1 : ${JsonConverter(mealData).stringify()}');
print('Json v2 : ${JsonConverterAlt(mealData).stringify()}');

Wrapping your class with the extension helps to resolve conflicts after they happen merely, even when the API is a bit much less fluid now.

Frequent Extension Usages

Now that you’ve got realized what Dart extensions are and methods to create them, it is time to see some frequent usages in actual apps.

Including Options to Lessons

Extensions allow you to add options to current Flutter and Dart courses with out re-implementing them.

Listed here are just a few examples:

  • Convert a Coloration to a hex String and vice versa.
  • Separating the kids of a ListView utilizing the identical Widget as a separator in the whole app.
  • Convert various milliseconds from an int to a extra humanly readable String.

You may as well add options to courses from exterior packages out there at pub.dev.

Folks typically put the code so as to add these options in Utils courses corresponding to StringUtils. You would possibly have already got seen that in some tasks, even in different languages.

Extensions present a great different to them with a extra fluid API. In case you select this method, your StringUtils code will turn into an extension as a substitute of a category. Listed here are just a few strategies you could possibly add to a StringUtils extension:

  • String firstLetterUppercase()
  • bool isMail()
  • bool isLink()
  • bool isMultiline(int lineLength)
  • int occurrences(String sample)

When writing a static technique, take into account whether or not an extension would work first. An extension would possibly provide the identical output however with a greater API. That is particularly good when that technique is helpful in a number of locations in your code. :]

Dart Extensions as Shortcuts

In Flutter, many widgets require the present BuildContext, such because the Theme and Navigator. To make use of a TextStyle outlined in your Theme throughout the construct() technique of your widgets, you will have to write down one thing like this:


That is not brief, and also you would possibly use it a number of instances in your app. You may create extensions to make that sort of code shorter. Listed here are just a few examples:

import 'package deal:flutter/materials.dart';

extension ThemeShortcuts on BuildContext {
  // 1.
  TextTheme get textTheme => Theme.of(this).textTheme;

  // 2.
  TextStyle? get headlineSmall => textTheme.headlineSmall;

  // 3.
  Coloration? get primaryColor => Theme.of(this).primaryColor;

This is a breakdown of the code above:

  1. You make the textTheme extra simply accessible:

// With out extension
// With extension
  1. Use your earlier textTheme technique to return a TextStyle. The code is clearly shorter:

// With out extension
// With extension
  1. You may add as many strategies as you’d wish to make shortcuts, corresponding to to get the primaryColor:

// With out extension
// With extension

Widespread Packages Utilizing Extensions

You would possibly already use standard packages that allow you to use extensions.

Routing packages typically use them to navigate instantly from BuildContext. In auto_route as an illustration, you possibly can go to the earlier web page with context.popRoute(). The identical goes with go_router, the place you need to use context.pop().

Translation packages present strategies on String through extensions to translate them to the proper language. With easy_localization, you possibly can name tr() in your String to translate it: whats up.tr(). You may even name it on Textual content: Textual content('whats up').tr().

State administration packages like Supplier additionally use them. For example, you possibly can watch a worth from a Supplier with context.watch()

You may even seek for extensions on pub.dev, and you will find packages that solely include extensions so as to add frequent options to native sorts or for use as shortcuts.

Extensions All over the place … Or not?

Dart extensions give superpowers to your courses. However with nice energy comes nice accountability.

Writing shorter code is not all the time the easiest way to make a challenge develop, particularly if you’re a part of a workforce. When engaged on a Flutter challenge, Flutter and Dart APIs are the frequent base each developer ought to know.

  1. In case you rely an excessive amount of on extensions, you possibly can lose familiarity with the final Flutter and Dart APIs.

You may need difficulties when becoming a member of new tasks the place extensions aren’t used. It’d take you longer to get aware of the challenge.

  1. Different builders should not aware of your extensions.

If different builders be part of your challenge, they could have issue understanding your code and following your practices. They will should study your extensions along with every little thing else they will must study, just like the enterprise and the structure.

Normally, use extensions however do not rely an excessive amount of on them.

The place to Go From Right here?

Obtain the finished challenge recordsdata by clicking the Obtain Supplies button on the high or backside of the tutorial. Now, it is best to higher perceive Dart extensions and methods to use them in your Flutter apps.

A package deal that makes heavy use of extensions is RxDart.. Study extra about it in RxDart Tutorial for Flutter: Getting Began.

We hope you loved this tutorial. You probably have any questions or feedback, please be part of the dialogue beneath!

Related Articles


Please enter your comment!
Please enter your name here

Latest Articles