Code generation
- Dart course
- Advanced
- Lesson 23/83
- 5 min
Learn code generation with source_gen.
Code generation with source_gen
source_gen is a package that generates Dart code from Dart code. It runs with build_runner; in a pre-compile step it produces .g.dart files.
It replaces reflection: it reads annotations and produces serialization/mapper code for the relevant class. There is no runtime cost; everything is ready before compilation.
Common uses: json_serializable (JSON ↔ class), freezed (immutable data classes), mockito (mock generation).
The Generator class
A source_gen generator implements the Generator abstract class: its generate(LibraryReader, BuildStep) method returns a String (Dart code).
The generator reads source code via the analyzer package (AST), finds annotations and produces methods/fields for the relevant class.
The generated file has the .g.dart extension and is written next to the original. It is included into the source file via the part directive.
Practice Simulate a simple code generator
Define class FieldGen { final String name; FieldGen(this.name); String build() => 'final String $name;'; }. Inside main create var g = FieldGen('title'); and add print(g.build());.
Starter code
void main() {
// define the FieldGen class (outside main)
// create an instance and print build() output
}Sample solution
class FieldGen {
final String name;
FieldGen(this.name);
String build() => 'final String $name;';
}
void main() {
var g = FieldGen('title');
print(g.build());
}Expected output
final String title;
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Build command
dart run ____ build
dart run build_runner build
Explanation: build_runner runs the code generation.
2 Match the tools
| Term | Meaning |
|---|---|
source_gen |
Code generation |
build_runner |
Build step |
analyzer |
AST reading |
.g.dart |
Generated file |
3 When does source_gen run?
- At runtime
- Only on the server
- In a pre-compile build step Correct answer
- Only in tests
Explanation: source_gen runs pre-compile via build_runner.