Dart Extensions Tutorial: Improve your Flutter Code

Learn how to take your Flutter skills to the next level and make your code reusable with one of Dart’s most useful features: Dart extensions. By Sébastien Bel.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Popular Packages Using Extensions

You might already use popular packages that let you use extensions.

Routing packages often use them to navigate directly from BuildContext. In auto_route for instance, you can go to the previous page with context.popRoute(). The same goes with go_router, where you can use context.pop().

Translation packages provide methods on String via extensions to translate them to the correct language. With easy_localization, you can call tr() on your String to translate it: hello.tr(). You can even call it on Text: Text('hello').tr().

State management packages like Provider also use them. For instance, you can watch a value from a Provider with context.watch()

You can even search for extensions on pub.dev, and you'll find packages that only contain extensions to add common features to native types or to be used as shortcuts.

Extensions Everywhere ... Or not?

Dart extensions give superpowers to your classes. But with great power comes great responsibility.

Writing shorter code isn't always the best way to make a project grow, especially when you're part of a team. When working on a Flutter project, Flutter and Dart APIs are the common base every developer should know.

  1. If you rely too much on extensions, you can lose familiarity with the general Flutter and Dart APIs.

You might have difficulties when joining new projects where extensions aren't used. It might take you longer to get familiar with the project.

  1. Other developers are not familiar with your extensions.

If other developers join your project, they might have difficulty understanding your code and following your practices. They'll have to learn your extensions in addition to everything else they'll need to learn, like the business and the architecture.

In general, use extensions but don't rely too much on them.

Where to Go From Here?

Download the completed project files by clicking the Download Materials button at the top or bottom of the tutorial. Now, you should better understand Dart extensions and how to use them in your Flutter apps.

A package that makes heavy use of extensions is RxDart.. Learn more about it in RxDart Tutorial for Flutter: Getting Started.

We hope you enjoyed this tutorial. If you have any questions or comments, please join the discussion below!

Sébastien Bel

Contributors

Sébastien Bel

Author

Michele Volpato

Tech Editor

Adriana Kutenko

Illustrator

Aldo Olivares

Final Pass Editor

Brian Moakley

Team Lead

Over 300 content creators. Join our team.