How to speed up code generation with build_runner in Dart & Flutter

Code generation has many use cases in our Flutter apps, including JSON serialization, navigation, and internationalization.

Packages like Freezed compensate for missing Dart language features such as sealed unions and offer many useful features.

Many Flutter packages rely on build_runner, a build system for Dart code generation.

Unfortunately, build_runner takes long time to run because by default it analyzes all the Dart source files in your project.

There are two ways to mitigate this:

  1. move all files that depend on codegen to a separate package
  2. add a build.yaml file that specifies a subset of files to be processed:
targets: $default: builders: freezed:freezed: generate_for: include: - lib/models/**.dart

Setting this up correctly can save you a lot of time in the long run. 👍

Extra Tip

You can use a suffix such as *.codegen.dart for all files that need to be processed by build_runner and update the build.yaml like this:

targets: $default: builders: freezed:freezed: generate_for: include: - lib/**.codegen.dart

This way you can place the files anywhere you want in your project.


This tip was inspired by this thread on Twitter.

Happy coding!

Want More?

Invest in yourself with my high-quality Flutter courses.

The Complete Dart Developer Guide

The Complete Dart Developer Guide

Learn Dart Programming in depth. Includes: basic to advanced topics, exercises, and projects. Fully updated to Dart 2.15.

Flutter Animations Masterclass - Full Course

Flutter Animations Masterclass - Full Course

Master Flutter animations and build a completely custom habit tracking application.

Flutter & Firebase Course: Build a Complete App for iOS & Android

Flutter & Firebase Course: Build a Complete App for iOS & Android

A full course with in-depth content, taking you from the basics all the way up to more advanced topics.

Flutter REST API Crash Course

Flutter REST API Crash Course

Build a Coronavirus Tracking App, and learn how to use REST APIs in Flutter.

Get the best Flutter tutorials, right in your inbox.

Join over 16,000 developers who receive my weekly Flutter email course & newsletter:

No spam, ever. Unsubscribe at any time.