Skip to content
Blog

Source Generation Patterns in Dart: Annotations, Builders, and When to Skip It

Patterns for build and source_gen: annotation-driven generators, consuming .g.dart files, isolating generated APIs, build.yaml tuning, and when to skip codegen.

Published on • November 12, 2026

AI Assistant

Code generation in Dart is a stack of three layers, and most problems come from confusing them: build (5.0.0) is the platform-agnostic asset graph, build_runner (2.17.1) is the CLI that executes it, and source_gen (4.3.1) is the developer-friendly framework on top for annotation-driven output. This post is about patterns, how to structure generators and their consumers, how to keep builds fast, and when hand-writing wins.

Anatomy of the stack

LayerPackageJob
Executionbuild_runner 2.17.1Watches files, runs builders, writes outputs
Asset graphbuild 5.0.0Builder interface, BuildStep, input/output tracking
Generator frameworksource_gen 4.3.1Generator, GeneratorForAnnotation, part-file convention
Concrete generatorjson_serializable 6.15.2Emits fromJson/toJson for @JsonSerializable classes

You normally touch only the bottom two rows. The build_runner code generation post covers the CLI and build.yaml basics; the Dart source_gen utilities post covers the generator API in depth.

Annotation-driven generators

The standard shape is GeneratorForAnnotation<T>, which visits every element annotated with T:

class RouteModelGenerator extends GeneratorForAnnotation<GenerateRoute> {
  @override
  Future<String> generateForAnnotatedElement(
    Element element,
    ConstantReader annotation,
    BuildStep buildStep,
  ) async {
    if (element is! ClassElement) return '';
    final path = annotation.read('path').literalValue as String;
    return 'RouteDef(\'${element.name}\', \'$path\');';
  }
}

Match types with TypeChecker.typeNamed(T, inPackage: 'my_package') so a same-named class from another package cannot slip in. Read annotation values with ConstantReader (isNull, literalValue, revive()) instead of the raw analyzer constant API.

Isolating generated code behind a handwritten API

Generated symbols are ugly and churn. Keep them behind a stable surface:

part 'invoice.g.dart';

@JsonSerializable()
class Invoice {
  factory Invoice.fromJson(Map<String, dynamic> json) =>
      _$InvoiceFromJson(json);

  Map<String, dynamic> toJson() => _$InvoiceToJson(this);
}

Callers depend on Invoice.fromJson, never on _$InvoiceFromJson. The same rule applies to a generated router or repository: expose one handwritten entry point, keep part directives and generated names private to the library. If you later swap the generator, no call site changes.

Incremental build pitfalls and tuning

build_runner only rebuilds what the graph says changed, so anything that invalidates shared inputs triggers a full run: editing build.yaml, bumping a builder package, or touching a widely imported part file. Tune with generate_for and builder options:

targets:
  $default:
    builders:
      json_serializable:
        generate_for:
          - lib/models/*.dart
        options:
          field_rename: snake
          explicit_to_json: true
      source_gen:combining_builder:
        options:
          ignore_for_file: [avoid_dynamic_calls]

Practical rules: run dart run build_runner build --delete-conflicting-outputs after upgrades, keep .dart_tool/ gitignored, split large models so only affected libraries rebuild, and never edit a .g.dart file because the next build overwrites it. If a build feels slow, check whether you are accidentally rebuilding the whole graph.

Testing generated code

Test the generator, not the build. build_test gives an in-memory harness:

await testBuilder(
  LibraryBuilder(RouteModelGenerator()),
  {'a|lib/page.dart': '@GenerateRoute(path: \'/home\') class Home {}'},
  outputs: {'a|lib/page.g.dart': decodedMatches(contains('Home'))},
);

Also add ordinary unit tests that round-trip your models through fromJson and toJson, because that is the behavior users actually depend on. Assert that a library with no annotations produces no output at all.

When to skip generation

Generation pays for itself when the code is mechanical, high-volume, and drifts easily: JSON codecs, copyWith, ==, hashCode, route tables, DI registrations, typed API clients. It costs a build step, a .g.dart in every pull request, analyzer noise, and onboarding friction for contributors who forget to run build_runner.

Skip it when any of these hold: the logic is under ~30 lines and rarely changes; it needs judgment or configuration per call site; the team cannot run the generator in CI reliably; or a language feature already covers it. Records, patterns, toString via a small mixin, and extension methods eliminate a surprising amount of what teams once generated. When a hand-written version is short enough to review in one screen, hand-write it.

Takeaway: Build annotation-driven generators with GeneratorForAnnotation and TypeChecker.typeNamed(..., inPackage:), hide every generated symbol behind one handwritten API, tune incremental builds with generate_for in build.yaml, test with build_test, and skip generation entirely for anything a reader can understand and maintain in a few lines.

Sources