source_gen 0.7.4

  • Installing
  • Versions
  • 96


Build Status Pub Package Version Join the chat on Gitter


source_gen provides utilities for automated source code generation for Dart:

  • A tool for generating code that is part of your Dart project.
  • A framework for creating and using multiple code generators in a single project.
  • A convention for human and tool generated Dart code to coexist with clean separation.

It's main purpose is to expose a developer-friendly API on top of lower-level packages like the analyzer or build. You don't have to use source_gen in order to generate source code; we also expose a set of library APIs that might be useful in your generators.

Quick Start Guide

Because source_gen is a package, not an executable, it should be included as a dependency in your project. If you are creating a generator for others to use (for example, a JSON serialization generator) or a library that builds on top of source_gen include it in your pubspec dependencies:


If you're only using source_gen in your own project to generate code, and then you publish that code (generated code included), then you can simply add as a dev_dependency:


Once you have source_gen setup, you should reference the examples below.

Creating a generator

Extend the Generator or GeneratorForAnnotation class and source_gen will call your generator for a Dart library or for each element within a library tagged with the annotation you are interested in.

Running generators

source_gen is based on the build package. Use a PartBuilder or LibraryBuilder to wrap your Generator as a Builder which can be run using a build system compatible with package:build. See the build package documentation for information on running Builders.


What is the difference between source_gen and build?

Build is a platform-agnostic framework for Dart asset or code generation that is pluggable into multiple build systems including barback (pub/dart transformers), bazel, and standalone tools like build_runner. You could also build your own.

Meanwhile, source_gen provides an API and tooling that is easily usable on top of build to make common tasks easier and more developer friendly. For example the PartBuilder class wraps one or more Generator instances to make a Builder which creates part of files, while the LibraryBuilder class wraps a single Generator to make a Builder which creates Dart library files.

What is the difference between source_gen and transformers?

Dart transformers are often used to create and modify code and assets as part of a Dart project.

Transformers allow modification of existing code and encapsulates changes by having developers use pub commands – run, serve, and build. Unfortunately the API exposed by transformers hinder fast incremental builds, output caching, and predictability, so we introduced builders as part of package:build.

Builders and source_gen provide for a different model: outputs must be declared ahead of time and code is generated and updated as part of a project. It is designed to create part or standalone files that augment developer maintained Dart libraries. For example AngularDart uses build and source_gen to "compile" HTML and annotation metadata into plain .dart code.

Unlike transformers, generated code MAY be checked in as part of your project source, although the decision may vary depending on project needs.

Generated code SHOULD be included when publishing a project as a pub package. The fact that source_gen is used in a package is an implementation detail.


  • Added typeNameOf, which is a safe way to get the name of a DartType, even when the type is a FunctionType, which has a null name in newer versions of the Dart analyzer.

  • Added LibraryReader.pathToUrl(Uri|String), which computes the import or export path necessary to reach the provided URL from the current library. Also added pathToAsset and pathToElement as convenience functions.

  • Expanded package:build support to allow version 0.12.0.


  • Allow null and empty outputs form GeneratorForAnnotation.


  • Allow package:build version 0.11.0


  • Support an optional header argument to PartBuilder and LibraryBuilder.



  • Return type of generate{ForAnnotatedElement} is now FutureOr<String>.


  • Added annotatedElements to return all elements annotated with something.
  • Added classElements getter for returning all class-es in a library.


  • Added hasAnnotationOf and hasAnnotationOfExact.


  • Added isAny (for consistency, but deprecated) and isLiteral.
  • Added literalValue as an alias for the now deprecated anyValue.
  • Allow literalValue to return null if the value is actually null.
  • Fixed a bug where a Symbol would return as a String for anyValue.
  • Fixed a bug where a List and Map were not considered literals.


  • Breaking changes: See the wiki for help upgrading.

    • Generator.generate now operates on a LibraryReader rather than being called for every Element within a library. Generators can iterate over elements using LibraryReader.allElements. GeneratorForAnnotation will continue to call generateForAnnotatedElement repeatedly for each element.
    • GeneratorForAnnotation passes in a ConstantReader for the annotation instance rather than re-creating it using mirrors.
    • GeneratorBuilder is replaced with PartBuilder and LibraryBuilder depending on whether the output is meant to be included in a part file.
    • Removed JsonSerializable and related classes. These are moved to package:json_serializable.
    • Removed lib/builder.dart. Import through source_gen.dart instead.
    • Removed OutputFormatter typedef.
  • Add LibraryReader.allElements - a utility to iterate across all Element instances contained in Dart library.

  • Add LibraryReader.element to get back to the LibraryElement instance.

  • Add ConstantReader.objectValue to get back to the DartObject instance.

  • Add ConstantReader.peek to read a value that returns null if not found:

// Tries to read the field "token" first, then "_token".
findTokenField(DartObject o) {
  final reader = new ConstantReader(o);
  final token = o.peek('token') ??'_token');
  • Add throwOnUnresolved optional parameter to TypeChecker.annotationsOf, TypeChecker.annotationsOfExact, TypeChecker.firstAnnotationOf, and TypeChecker.firstAnnotationOfExact. Setting this to false will enable you to check for matching annotations with incomplete type information (at your own risk).
  • Builder logs now log the primary inputs AssetId instead of the library, which is more useful for tracking down the actual files.


  • Tighten constraint on source_span.


  • Added spanForElement; returns a SourceSpan for an analyzer Element.
  • Logs a warning to the console when a GeneratorBuilder outputs a part file for a given input, but that input does not define part 'name.g.dart';.


  • Breaking change: TypeChecker#annotationsOf|firstAnnotationOf now returns annotations that are assignable to the TypeChecker's type. As a result we've added #annotationsOfExact|firstAnnotationOfExact which has the old behavior for precise checks.
  • TypeChecker#annotations...-methods now throw a StateError if one or more annotations on an element are not resolvable. This is usually a sign of a misspelling, missing import, or missing dependency.
  • Added TypeChecker.any, which delegates to multiple other TypeChecker implementations when making a type check.


  • Update minimum analyzer package to 0.29.10.


  • Bug fixes:
    • Do not fail when "library" is omitted but nothing would be output.
    • Do not fail on extensions that don't end in ".dart" (valid use case).


  • Update the minimum Dart SDK to 1.22.1.

  • Deprecated builder.dart: import source_gen.dart instead.

  • Added TypeChecker, a high-level API for performing static type checks:

    import 'package:analyzer/dart/element/type.dart';
    import 'package:source_gen/source_gen.dart';
    void checkType(DartType dartType) {
      // Checks compared to runtime type `SomeClass`.
      print(const TypeChecker.forRuntime(SomeClass).isExactlyType(dartType));
      // Checks compared to a known Url/Symbol:
      const TypeChecker.forUrl('package:foo/foo.dart#SomeClass');
      // Checks compared to another resolved `DartType`:
      const TypeChecker.forStatic(anotherDartType);
  • Failing to add a library directive to a library that is being used as a generator target that generates partial files (part of) is now an explicit error that gives a hint on how to name and fix your library:

    > Could not find library identifier so a "part of" cannot be built.
    > Consider adding the following to your source file:
    > "library;"

    In Dart SDK >=1.25.0 this can be relaxed as part of can refer to a path. To opt-in, GeneratorBuilder now has a new flag, requireLibraryDirective. Set it to false, and also set your sdk constraint appropriately:

      sdk: '>=1.25.0 <2.0.0'
  • Added LibraryReader, a utility class for LibraryElement that exposes high-level APIs, including findType, which traverses export directives for publicly exported types. For example, to find Generator from package:source_gen/source_gen.dart:

    void example(LibraryElement pkgSourceGen) {
      var library = new LibraryReader(pkgSourceGen);
      // Instead of pkgSourceGen.getType('Generator'), which is null.
  • Added ConstantReader, a high-level API for reading from constant (static) values from Dart source code (usually represented by DartObject from the analyzer package):

    abstract class ConstantReader {
      factory ConstantReader(DartObject object) => ...
      // Other methods and properties also exist.
      /// Reads[ field] from the constant as another constant value.
      ConstantReader read(String field);
      /// Reads [field] from the constant as a boolean.
      /// If the resulting value is `null`, uses [defaultTo] if defined.
      bool readBool(String field, {bool defaultTo()});
      /// Reads [field] from the constant as an int.
      /// If the resulting value is `null`, uses [defaultTo] if defined.
      int readInt(String field, {int defaultTo()});
      /// Reads [field] from the constant as a string.
      /// If the resulting value is `null`, uses [defaultTo] if defined.
      String readString(String field, {String defaultTo()});


  • Add formatOutput optional parameter to the GeneratorBuilder constructor. This is a lambda of the form String formatOutput(String originalCode) which allows you do do custom formatting.


  • Support for package:analyzer 0.30.0


  • Support for package:build 0.9.0


  • Support package:build 0.8.x
  • Less verbose errors when analyzer fails to resolve the input.


  • Support the latest release of pkg/dart_style.


  • Use the new log field instead of the deprecated buildStep.logger


  • Give more information when dartfmt fails.


  • Update to latest build, build_runner, and build_test releases.


  • BugFix: Always release the Resolver instance, even when generation does not run


  • Don't throw when running against a non-library asset and getting no LibraryElement


  • Add matchTypes method. As with anything imported from /src/ this is use-at-your-own-risk since it is not guaranteed to be stable
  • Internal cleanup
    • Drop some unused utility methods
    • Move cli_util to dev_dependencies
    • Avoid some deprecated analyzer apis
    • Syntax tweaks
    • Drop results.dart which had no usages


  • Use library URIs (not names) to look up annotations in the mirror system.
  • Loosen version constraint to allow package:build version 0.6
  • Fix a bug against the latest SDK checking whether List implements Iterable


  • Generate valid strong-mode code for typed lists.


  • Support the latest version of pkg/build.


  • Remove "experimental" comment in


  • Support package:analyzer 0.29.0


  • Upgrade to be compatible with the breaking changes in analyzer 0.28.0


  • Avoid calling computeNode() while instantiating annotation values


  • Support the latest version of build package.


  • Added GeneratorBuilder option isStandalone to generate files that aren't part of source file.


  • Fixed multi-line error output.


  • Remove an outdated work-around.

  • Make strong-mode clean.


  • Support the latest version of pkg/build.


  • Breaking: Switch to the build package for running Generators. This means that the top level build and generate functions are no longer available, and have been replaced by the top level build, watch, and serve functions from the build package, and the GeneratorBuilder class. See tool/build.dart, tool/watch.dart, and tool/phases.dart for usage.

    • Note that the build package is experimental, and likely to change.
  • Breaking: The build package provides an abstraction for reading/writing files via the BuildStep class, and that is now also provided to Generator#generate and GeneratorForAnnotation#generateForAnnotatedElement as a second argument.

  • Timestamps are no longer included in generated code.

  • There is no longer a need to specify the files related to an individual generator via AssociatedFileSet. Simply use the BuildStep instance to read and write files and the build package will track any files you read in and run incremental rebuilds as necessary.


  • Added support for Symbol and Type in annotations.

  • Improved error output when unable to create an instance from an annotation.


  • Upgrade to analyzer '^0.27.1' and removed a work-around for a fixed analyzer issue.


  • Upgrade to analyzer '^0.27.0'.


  • JsonSerializableGenerator now supports classes with read-only properties.


  • JsonSerializable: Added JsonKey annotation.

  • Improved output of generation errors and stack traces.

  • Require analyzer '^0.26.2'.


  • Handle null values for List properties.


  • JsonSerializable: add support for List values.


  • Updated to highlight the build_system package and de-emphasize Dart Editor.


  • Added omitGenerateTimestamp and followLinks named args to build.

  • Added followLinks to generate.


  • Update tests to use a more reliable method to find the current package root.


  • Require Dart 1.12.

  • Add implicit support for .packages. If the file exists, it is used. If not, we fall back to using the packages directory.

  • Support the latest releases of analyzer and dart_style packages.


  • Use fromJson if it's defined in a child field.


  • Match annotations defined in parts. Thanks, Greg!


  • Support the latest release of analyzer and args.


  • Analysis no longer parses function bodies. This greatly speeds up generation, but it could break any usage that needs function bodies.


  • Fixed


  • Updates for move to dart-lang org on GitHub.


  • BREAKING Returning a descriptive value from generate.

  • BREAKING Fixed incorrectly named argument omitGenerateTimestamp.

  • JsonSerializable: Handle dynamic and var as field types.


  • Added associatedFileSet to Generator. Allows a generator to specify that changes to any file in a directory next to a Dart source file can initiate a generation run.


  • Use async *. Requires SDK >= 1.9.0-dev.10

  • Protect against crash during code format.


  • Added omitGenerateTimestamp (incorrectly spelled) named argument to generate method.

  • Generator.generate is now called with the LibraryElement, too.


  • Fixed critical bug affecting annotation matching. #35

  • Started using published dart_style package.


  • Tweaks to JsonGenerator to address #31 and #32


  • Updated with new examples.
  • Fixed sub-bullet indenting in


  • BREAKING Moved and renamed JSON serialization classes.
  • Added a JsonLiteral generator.
  • Improved handling and reporting of Generator errors.
  • JsonGenerator
    • Learned how to use constructor arguments.
    • Learned how to properly handle DateTime.


  • Support for parametrized annotations.
  • Add named arguments to JsonGenerator.


  • updates.


  • BREAKING Generator.generate is now async – returns Future<String>
  • Big update to


  • Ready for experimentation.


  • First play release.

1. Depend on it

Add this to your package's pubspec.yaml file:

  source_gen: "^0.7.4"

2. Install it

You can install packages from the command line:

with pub:

$ pub get

Alternatively, your editor might support pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:source_gen/source_gen.dart';
Version Uploaded Documentation Archive
0.7.4 Jan 18, 2018 Go to the documentation of source_gen 0.7.4 Download source_gen 0.7.4 archive
0.7.3 Dec 14, 2017 Go to the documentation of source_gen 0.7.3 Download source_gen 0.7.3 archive
0.7.2+1 Nov 2, 2017 Go to the documentation of source_gen 0.7.2+1 Download source_gen 0.7.2+1 archive
0.7.2 Oct 9, 2017 Go to the documentation of source_gen 0.7.2 Download source_gen 0.7.2 archive
0.7.1 Aug 14, 2017 Go to the documentation of source_gen 0.7.1 Download source_gen 0.7.1 archive
0.7.0 Jul 26, 2017 Go to the documentation of source_gen 0.7.0 Download source_gen 0.7.0 archive
0.6.1+1 Jul 18, 2017 Go to the documentation of source_gen 0.6.1+1 Download source_gen 0.6.1+1 archive
0.6.1 Jul 11, 2017 Go to the documentation of source_gen 0.6.1 Download source_gen 0.6.1 archive
0.6.0 Jul 6, 2017 Go to the documentation of source_gen 0.6.0 Download source_gen 0.6.0 archive
0.5.10+1 Jun 28, 2017 Go to the documentation of source_gen 0.5.10+1 Download source_gen 0.5.10+1 archive

All 68 versions...


This feature is new.
We welcome feedback.
More details: scoring.

We analyzed this package, and provided a score, details, and suggestions below.

  • completed on Jan 21, 2018
  • Dart: 2.0.0-dev.15.0
  • pana: 0.10.0


Describes how popular the package is relative to other packages. [more]
92 / 100
Code health derived from static analysis. [more]
100 / 100
Reflects how tidy and up-to-date the package is. [more]
100 / 100
Overall score:
Weighted score of the above. [more]


Detected platforms: other

Primary library: package:source_gen/source_gen.dart.


  • The description is too short.

    Add more detail about the package, what it does and what is its target use case. Try to write at least 60 characters.

  • Package is pre-v1 release.

    While there is nothing inherently wrong with versions of 0.*.*, it usually means that the author is still experimenting with the general direction API.

  • Maintain an example.

    Create a short demo in the example/ directory to show how to use this package. Common file name patterns include: main.dart, example.dart or you could also use source_gen.dart.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.22.1 <2.0.0
analyzer >=0.29.10 <0.31.0 0.30.0+4 0.31.0-alpha.2
build >=0.10.0 <0.13.0 0.12.0
dart_style >=0.1.7 <2.0.0 1.0.9
meta ^1.1.0 1.1.2
path ^1.3.2 1.5.1
source_span ^1.4.0 1.4.0
Transitive dependencies
args 1.2.0
async 2.0.3
charcode 1.1.1
convert 2.0.1
crypto 2.0.2+1
csslib 0.14.1
front_end 0.1.0-alpha.4.1 0.1.0-alpha.7
glob 1.1.5
html 0.13.2+2
isolate 1.1.0
kernel 0.3.0-alpha.1.1 0.3.0-alpha.4
package_config 1.0.3
plugin 0.2.0+2
string_scanner 1.0.2
typed_data 1.1.5
utf 0.9.0+3
watcher 0.9.7+6
yaml 2.1.13
Dev dependencies
build_test >0.9.0 <0.11.0
cli_util >=0.1.0 <0.2.0 0.1.2+1
collection ^1.1.2 1.14.5
logging ^0.11.3 0.11.3+1
test ^0.12.3