Dart Code Generation#
A comprehensive reference for building Dart code generators using build_runner, source_gen, and the Dart analyzer.
What's Inside#
Core#
-
Build System — The
buildpackage interfaces:Builder,BuildStep,AssetId,Resolver, and more. - build.yaml Reference — Full configuration reference for declaring builders, targets, and options.
- Package Structure — How to organize a generator package with proper exports and dependencies.
Code Generation#
-
Analyzer API — Navigate the Dart element model:
LibraryElement,ClassElement,DartType, and visitors. -
source_gen — Higher-level abstractions:
GeneratorForAnnotation,LibraryGenerator, and output formatting. -
Approaches — Side-by-side comparison of raw
Builder,source_gen, and annotation-driven patterns. -
Annotations — Defining, reading, and validating custom annotations with
ConstantReader.
Practical#
- Complete Recipes — End-to-end examples: JSON serializer, route generator, DI container, and more.
- Testing — Unit and integration testing strategies for generators.
- Debugging — Troubleshooting build failures, attach a debugger, and common pitfalls.