Macro
- Dart course
- Advanced
- Lesson 22/83
- 5 min
Learn the Dart 3 macro experiment.
Macros (Dart 3)
Dart 3 introduced an experimental macro system. Macros generate code at compile time: when you annotate a class, the compiler injects methods/fields automatically.
Unlike previous approaches, macros are embedded in the compiler; they need no separate build_runner step. This speeds up the dev loop.
Since they are still experimental, the API may change. For production, source_gen (code generation) is still recommended; macros are promising.
Marking with annotations
Macros are triggered by annotations (metadata). When you add @MyMacro() to a class, the compiler runs the macro definition and injects the generated code.
Annotations in Dart are classes with a const constructor. Example: class Generated { const Generated(); }. Then @Generated() class Service {}.
Even without macros, annotations can be read at runtime via mirrors; but this does not work in Flutter/AOT.
Practice Define and apply an annotation
Define the annotation class class Generated { const Generated(); }. Define class Service {} marked with @Generated(). Inside main add print(Service().runtimeType);.
Starter code
void main() {
// define the Generated annotation class (const constructor)
// define a Service class marked with the annotation
// print the type name of a Service instance
}Sample solution
class Generated {
const Generated();
}
@Generated()
class Service {}
void main() {
print(Service().runtimeType);
}Expected output
Service
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When do macros generate code?
- At runtime
- At compile time Correct answer
- Only in tests
- On the server
Explanation: macros generate code at compile time.
2 Match the approaches
| Term | Meaning |
|---|---|
Macro |
Compile time |
source_gen |
Build step |
dart:mirrors |
Runtime |
runtimeType |
Basic type |
3 Apply an annotation
@____()
class Service {}
@Generated()
class Service {}
Explanation: @Generated() is added as an annotation to the class.