source_gen
- Dart course
- Expert
- Lesson 27/47
- 5 min
Learn source code generation with source_gen.
source_gen
source_gen is a framework built on top of Builder. It provides a high-level API for analyzing Dart source (via the analyzer) and generating code.
Two core classes: Generator (returns generated code from source) and GeneratorForAnnotation<T> (processes only classes marked with @T).
Usage: define an annotation, write a Generator, wrap it with SharedPartBuilder, run build_runner. The generated code is written to a .g.dart file.
GeneratorForAnnotation
GeneratorForAnnotation<T> processes only classes marked with @T. The generateForAnnotatedElement method is called for each marked class.
The method takes an Element (class info) and a ConstantReader (annotation values). It returns the generated code as a String.
This pattern eliminates hand-written fromJson/toJson. You add an annotation, the Generator produces the code. json_serializable uses this approach.
Practice Define an annotation and a generator
Define the annotation class class GenAnnotation { const GenAnnotation(); String get name => 'GenAnnotation'; }. Define String generateFor(GenAnnotation a) => '// generated for ${a.name}';. In main create const a = GenAnnotation(); and add print(generateFor(a));.
Starter code
void main() {
// define the GenAnnotation class (const constructor, name getter)
// define the generateFor function
// create an annotation; print via generateFor
}Sample solution
class GenAnnotation {
const GenAnnotation();
String get name => 'GenAnnotation';
}
String generateFor(GenAnnotation a) => '// generated for ${a.name}';
void main() {
const a = GenAnnotation();
print(generateFor(a));
}Expected output
// generated for GenAnnotation
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the source_gen parts
| Term | Meaning |
|---|---|
Generator |
Base class |
GeneratorForAnnotation |
Annotation-based |
@GenAnnotation |
Marker |
generate(...) |
Generating method |
2 What does GeneratorForAnnotation do?
- Parses YAML
- Writes .g.dart directly
- Runs the analyzer
- Generates code for annotated classes Correct answer
Explanation: GeneratorForAnnotation processes only annotated classes.
3 Generator inheritance
class MyGenerator extends ____<GenAnnotation> { }
class MyGenerator extends GeneratorForAnnotation<GenAnnotation> { }
Explanation: GeneratorForAnnotation provides annotation-based generation.