Dart
Analyzer
Learn the dart analyzer and plugins.
Analyzer
The analyzer package parses Dart source code into a syntax tree (AST). It is the foundation of code generation and lint checks.
parseString(content: ...) returns a ParseStringResult; the .unit field gives the CompilationUnit (AST root). To traverse nodes, the visitor pattern is used.
RecursiveAstVisitor<T> walks every node; you override methods like visitClassDeclaration, visitMethodDeclaration. This is the standard way to analyze code programmatically.
The visitor pattern
The visitor pattern lets you walk AST nodes by type. Each node type triggers a separate visit... method.
Example: to collect class names, you override visitClassDeclaration. For each class declaration you add the name to a list.
This pattern is common in code analysis and generation. Many tools, including source_gen and custom_lint, use the analyzer's visitor API.
Exercise Define a class name collector
Define an ElementInfo class with final String name; ElementInfo(this.name);. Define a ClassCollector class with final List<ElementInfo> classes = []; field and void add(String name) => classes.add(ElementInfo(name)); method. In main create final collector = ClassCollector();; call collector.add('User') and collector.add('Book'); print collector.classes.length; then print names with for (final e in collector.classes) { print(e.name); }.
Show example solution
class ElementInfo {
final String name;
ElementInfo(this.name);
}
class ClassCollector {
final List<ElementInfo> classes = [];
void add(String name) => classes.add(ElementInfo(name));
}
void main() {
final collector = ClassCollector();
collector.add('User');
collector.add('Book');
print(collector.classes.length);
for (final e in collector.classes) {
print(e.name);
}
}
Test yourself
-
What does the analyzer produce?
- An AST (syntax tree)
- A compiled binary
- A minified bundle
- A test report
Show answer
An AST (syntax tree) — the analyzer parses source into an AST.
-
Match the analyzer parts
- parseString()
- Source parsing
- CompilationUnit
- AST root
- RecursiveAstVisitor
- Visitor base
- LibraryElement
- Library element
-
Visitor inheritance
class MyVisitor extends Recursive____Visitor<void> { }
Show answer
class MyVisitor extends RecursiveAstVisitor<void> { }
Next lesson: Custom lint