Dart Extensions Tutorial: Enhance your Flutter Code


Discover ways to take your Flutter expertise to the subsequent degree and make your code reusable with certainly one of Dart’s most helpful options: Dart extensions.

You may have already got change into acquainted with primary Flutter and Dart information. You may even have your first app already revealed. But there may be at all times room for enchancment. Dart Extensions will help make your code smoother and simplify some code utilization.

This tutorial gained’t educate you how you can make a full Flutter app; the bottom is already performed. Your job will probably 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 varieties.
  • Recommendation on when to make use of them and when to not.
Observe: This Dart extensions tutorial assumes you realize the fundamentals of Dart and Flutter improvement. For those who’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 gadgets and internet browsers.

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

Have a look at the information in lib.

The content of the lib folder

First, open lib/knowledge/meal_data.dart. This can be a knowledge class holding your cat’s meal knowledge.

Proceed with lib/widgets/counter.dart. This can be 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 kind to kind the beneficial quantity of meals for a cat of a given weight. Observe 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 primarily based on MealData.

Lastly, open lib/predominant.dart. This incorporates the core of your app.

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

Construct and run the challenge. You must see a software 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 adjustments because of this.

What Is an Extension Technique?

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


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

You may additionally use them to create shortcuts.

Comparability with Options

When you possibly can’t change a category however wish to add a function associated to it, you could have three choices:

  1. Use a world or a static technique
  2. Use a wrapper across the desired class and create the strategy 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 {
  ultimate 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 principle 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 offers a extra fluid API. It feels prefer it’s a traditional technique from the bottom class.

Creating and Utilizing a Fundamental Extension

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


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

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

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

  String get hi there => 'hi there $aString';

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

An extension has a reputation and extends a selected 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 check with 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.

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

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

You create an object of the prolonged class utilizing a standard constructor. Then, you invoke the strategies and the operators outlined within the extension as in the event that they have been outlined within the authentic 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. For those who’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() {
    ultimate firstLetter = substring(0, 1);
    ultimate 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” primarily based on the MealType. The road beneath transforms the identify of the MealType enum to uppercase.

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

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

Begin by importing StringCaseConverter:

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

Now, change the foodType task with the next:

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

Solely the primary letter will probably be uppercase now.

Sizzling reload and see the up to date title:

Updated Wet and Dry titles

Observe the cat’s weight remark that seems when you set it to a worth larger than 7.

Superior Usages

Dart extensions can go manner past easy String transformations. You may lengthen nullable varieties and generics and may 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.

Have a look at the _catWeightCommentBuilder() technique in lib/predominant.dart.

For those who’d like to make use of firstLetterUppercase() on _catWeightComment, you’d need to take care of the truth that the _catWeightComment variable is nullable.

It might appear like this:


Observe the ? to deal with nullable values.

However there’s an excellent simpler method: You can also make extensions on nullable varieties.

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

extension StringCaseConverter on String? {
  String firstLetterUppercase() {
    if (this == null || this!.isEmpty) {
      return '';
    } else {
      ultimate firstLetter = this!.substring(0, 1);
      ultimate 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/predominant.dart and alter _catWeightCommentBuilder() to make use of the up to date extension:

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

Don’t neglect 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 lessons and strategies, you possibly can create Dart extensions on generic varieties. You’ll make one to insert a component between every authentic listing aspect.

Add a separator between each element of a list

Within the image above, the unique listing incorporates numbers you wish to separate by a comma. That is what you wish to obtain together 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 listing.

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) {
    ultimate 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. Observe that each the Listing and the brand new aspect needs to be of kind T.

This is an instance of how you can use it:

ultimate myExampleList = <String>['Sam', 'John', 'Maya'];
print(myExampleList.separated(', ').be a 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/predominant.dart, find the _mainColumnContent() technique. It returns the kids of the primary Column of your widget tree. Observe the house variable on the technique’s starting.

const house = SizedBox(top: 20);

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

Now, it’s good to use the brand new extension. Find the remark TODO Add separation between objects with an extension and change your entire line with the code beneath.

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

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

Once more, remember to import the extension.

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

You may also make an extension technique straight on Listing<Widget> quite 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, top: 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 an inventory of widgets. The extension defines a few strategies that add house among the many widgets within the listing.

Some necessary 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 potential to reuse different extensions in an extension, like SeparatedList is utilized in SpacedWidgets.

Bear in mind to import the lacking references.

import 'bundle:flutter/widgets.dart';

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

// Substitute
].separated(const SizedBox(top: 20));

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

You are now utilizing SpacedWidgets as a substitute of SeparatedList.

Non-public Dart Extensions

Like lessons, 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 predominant.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 predominant.dart file.

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

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

Nonetheless, naming an extension make it simpler to grasp what it does. Furthermore, it offers you a better method to handle conflicts, as you will see later.

Though it would sound good to make non-public extensions, you must 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 Features, Constructors and Factories

Dart extensions aren’t but good. They can not:

  • 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 'Hiya 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 may disappoint you:

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

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

// Works!

You may’t use String to name helloWorld(). It’s a must to use StringPrinter straight, which is not best. With the ability to name String.helloWorld() was the preliminary intention, in spite of everything.

For the CatFoodCalculator app, you may need favored 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 'bundle: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,
    Colour? activeColor,
    Colour? inactiveColor,
    Colour? thumbColor,
    MouseCursor? mouseCursor,
    String Operate(double)? semanticFormatterCallback,
    FocusNode? focusNode,
    bool autofocus = false,
    required SliderThemeData themeData,
  }) {
    return SliderTheme(
      knowledge: themeData,
      baby: 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 straight.

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

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

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

baby: 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: Colour(0xffffa938),

It’s a must to name ThemedSlider.withTheme() as a substitute of Slider.withTheme(). This limitation is actively mentioned in a GitHub subject.

Dart Extensions on Enums

Moreover lessons, you can even create extensions on enum.

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

The quantity of meals you must feed to your cat is determined by the precise meals, and the bundle often exhibits the beneficial day by day consumption. One may not know the place to search out the proper data to kind on this kind. 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 adjustments primarily based on the MealType. In your subsequent extension, you will create a way to indicate this popup.

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

import 'bundle:flutter/materials.dart';

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

extension MealTypeDialog on MealType {
  Future<void> infoPopup(BuildContext context) {
    ultimate textual content = this == MealType.moist
        ? 'Yow will discover this knowledge printed on the pack of moist meals'
        : 'Your bag of dry meals ought to have this knowledge 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 while you use the onInfoPressed() technique from _MealInfoState. It exhibits a distinct textual content primarily based 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 Substitute onInfoPressed with an extension remark and change 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 straight by calling a way on an enum.

Dealing with Conflicts

The CatFoodCalculator app is kind of easy: There isn’t any API name nor native storage. If you would like to implement it, changing your objects to JSON is an efficient place to begin. A technique 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(). Observe that the extension is dynamic: It is obtainable to every kind, 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 your entire job.

In predominant.dart, discover the // TODO add a save button right here remark and change 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() {
  ultimate 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 you must learn within the console:

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

Another stringify technique might embody the kind of the article 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 way named stringify(). In an actual app, this may occur on account of utilizing an exterior library.

Return to predominant.dart and observe the error on stringify():

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

One method to remedy it’s to make use of the conceal function within the import:

import 'utils/json_converter.dart' conceal JsonConverterAlt;

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

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

ultimate 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 have realized what Dart extensions are and how you can 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 lessons with out re-implementing them.

Listed here are a couple of examples:

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

You may also add options to lessons from exterior packages obtainable at pub.dev.

Individuals typically put the code so as to add these options in Utils lessons similar to StringUtils. You may have already got seen that in some tasks, even in different languages.

Extensions present an excellent various to them with a extra fluid API. For those who select this method, your StringUtils code will change into an extension as a substitute of a category. Listed here are a couple of strategies you may add to a StringUtils extension:

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

When writing a static technique, contemplate whether or not an extension would work first. An extension may provide the similar 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 jot down one thing like this:


That is not quick, and also you may use it a number of instances in your app. You may create extensions to make that form of code shorter. Listed here are a couple of examples:

import 'bundle:flutter/materials.dart';

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

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

  // 3.
  Colour? 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 prefer to make shortcuts, similar to to get the primaryColor:

// With out extension
// With extension

In style Packages Utilizing Extensions

You may already use fashionable packages that allow you to use extensions.

Routing packages typically use them to navigate straight 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 should 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: hi there.tr(). You may even name it on Textual content: Textual content('hi there').tr().

State administration packages like Supplier additionally use them. As an 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 varieties or for use as shortcuts.

Extensions In all places … Or not?

Dart extensions give superpowers to your lessons. However with nice energy comes nice duty.

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

  1. For those who 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 would take you longer to get acquainted with the challenge.

  1. Different builders usually are not acquainted with your extensions.

If different builders be a part of your challenge, they may have problem understanding your code and following your practices. They’re going to need to be taught your extensions along with every thing else they will must be taught, just like the enterprise and the structure.

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

The place to Go From Right here?

Obtain the finished challenge information by clicking the Obtain Supplies button on the high or backside of the tutorial. Now, you must higher perceive Dart extensions and how you can use them in your Flutter apps.

A bundle that makes heavy use of extensions is RxDart.. Be taught extra about it in RxDart Tutorial for Flutter: Getting Began.

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


Please enter your comment!
Please enter your name here