Summary - Metaprogramming
- Dart course
- Advanced
- Lesson 24/83
- 5 min
Combine reflection, mirrors and source_gen to write a code generator.
Summary - Metaprogramming
This group surveyed Dart's metaprogramming tools: dart:mirrors (runtime reflection), runtimeType (basic type info), Function.apply (dynamic invocation), macros (Dart 3, compile time), source_gen (build-step code generation).
Practical choice: source_gen for Flutter/AOT (json_serializable, freezed); dart:mirrors for the Dart VM; macros for the future.
Each tool has a different cost: mirrors are slow at runtime, source_gen costs pre-compile but is free at runtime.
Practice Summary: square via Function.apply
Define a top-level int square(int x) => x * x; function. Inside main add var r = Function.apply(square, [5]); and print(r);.
Starter code
void main() {
// define the square function (outside main)
// call square(5) via Function.apply; print it
}Sample solution
int square(int x) => x * x;
void main() {
var r = Function.apply(square, [5]);
print(r);
}Expected output
25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Best option for Flutter?
- manual code
- dart:mirrors
- only runtimeType
- source_gen Correct answer
Explanation: source_gen works in Flutter/AOT and has no runtime cost.
2 Match the tools
| Term | Meaning |
|---|---|
dart:mirrors |
Runtime reflection |
source_gen |
Build step |
Function.apply |
Dynamic call |
runtimeType |
Type info |
3 Dynamic function call
var r = ____(add, [3, 4]);
var r = Function.apply(add, [3, 4]);
Explanation: Function.apply equals add(3,4).