Reducing Build Runner Code Generation Time in Flutter

Mustafa Ali Dikçinar
Team Kraken
Published in
2 min readJul 29, 2024

Flutter is a popular framework for building cross-platform mobile applications. One of the challenges that developers face when working with Flutter is build runner time. The build runner is responsible for running tasks such as code generation, compilation, and other tasks required to build the application. The build runner time can be a bottleneck, especially during development, where developers need to rebuild the application frequently. In this article, we will explore a simple strategy that developers can use to reduce build runner time in Flutter.

Use builders to generate code for multiple folders

If you have code generation tasks that need to be performed on multiple folders, you can use Builders. Builders allow developers to define custom code generation tasks and associate them with specific directories in their project. To use Builders, developers need to define a build.yaml file in the root directory of their project. The build.yaml file contains configuration information for the Builder, including the directories it should operate on and the commands it should execute.

Here’s an example build.yaml file that defines a Builder that generates code for specified folders and files.

targets:
$default:
builders:
json_serializable:
enabled: true
options:
field_rename: snake
generate_for:
- "lib/core/**"
- "lib/features/**"
injectable_generator|injectable_builder:
enabled: true
generate_for:
- "lib/**"
envied_generator|envied:
generate_for:
- "lib/env.dart"
auto_route_generator|autoRouteGenerator:
enabled: true
generate_for:
- "lib/routes/router.dart"

Example contains builders for these packages
JsonSerializable: For handling JSON. The builders generate code when they find members annotated with classes defined in json_annotation.
InjectableGenerator: A generator for injectable library.
EnviedGenerator: A generator for for envied library.
AutoRouteGenerator: A generator for auto_route library.

Also the files that includes code generation can be tagged with *.gen.dart and set generate for path for that files. This will also help to reduce the code generation time.

Read more about build.yaml files.

Conclusion

With this simple strategy our Build Runner code generation time is reduced about half.

Before — After

🎉 Thanks for reading my article.

⭐️ I also would like to thank Team Kraken review this article.

💙 You can find me on Twitter, Linkedin and Github.

--

--