pub package Build Status Coverage Status

code_builder is a fluent Dart API for generating valid Dart source code.

Code generation was traditionally done through a series of package-specific string concatenations which usually results in messy and sometimes invalid Dart code that is not easily readable and is very difficult to refactor.

code_builder uses the analyzer package to create real Dart language ASTs, which, while not guaranteed to be correct, always follows the analyzer's own understood format.


If a feature is missing (the Dart language is always evolving) or you'd like an easier or better way to do something, consider opening a pull request. You can always file an issue, but generally speaking feature requests will be on a best-effort basis.


Code builder has a narrow and user-friendly API.

For example creating a class with a method:

var base = reference('Organism');
var clazz = new ClassBuilder('Animal', asExtends: base);
  new MethodBuilder.returnVoid(
    returns: reference('print').call([literal('Yum')]),


class Animal extends Organism {
  void eat() => print('Yum!');

Have a complicated set of dependencies for your generated code? code_builder supports automatic scoping of your ASTs to automatically use prefixes to avoid symbol conflicts:

var lib = new LibraryBuilder.scope()
    new MethodBuilder(
      returnType: reference('Thing', 'package:thing/thing.dart'),
    new MethodBuilder(
      returnType: reference('Thing', 'package:thing/alternative.dart'),


import 'package:thing/thing.dart' as _i1;
import 'package:thing/alternative.dart' as _i2;

_i1.Thing doThing() {}
_i2.Thing doOtherThing() {}




Contains references to the dart:async SDK for use in code generation.


Contains references to the dart:core SDK for use in code generation.