code_builder
A fluent, builder-based library for generating valid Dart code.
4.11.1
8.3M downloads/mo
#60 most downloaded on pub.dev
dart-lang/tools
What this package is like to depend on
Last release 7 months ago
05 Jan 2026
Release timing varies
gaps range from 3 weeks to 11 months
Nearly every release is documented
notes for 40 of 42 stable releases
Nothing withdrawn
no release was ever pulled
10 years old
62 releases · first in 2016
2 releases in the last 12 months
see the full history below
Release timeline
62 releases · Sep 2016 to Jan 2026Releases
latest 60 of 62-
4.11.105 Jan 2026Release notes
Open source →- Convert imports of implementation libraries under
package:fixnum/src/*into imports ofpackage:fixnum/fixnum.dartto prevent issues when version 1.2.0 is released with platform-specific implementation libraries that generated code should not import directly. This is a temporary workaround, it will be replaced by a new way of managing imports in a future major version release.
- Convert imports of implementation libraries under
-
4.11.010 Sep 2025Release notes
Open source →- Export
SpecVisitor,ClosureExpression,LiteralMapExpressionLiteralRecordExpression,LiteralSetExpressiontypes. - Support
Expression.newInstanceNamedwith empty name - Consistently add blank lines between
=>in class-like definitions. - Fixed bug: Fields declared with
staticandexternalnow produce code with correct order - Require
built_collection: ^5.1.1 - Require
built_value: ^8.10.1 - Require
collection: ^1.19.0 - Require
matcher: ^0.12.16+1 - Require
meta: ^1.16.0 - Require
sdk: ^3.7.0
- Export
-
4.10.129 Oct 2024Release notes
Open source →- Require Dart
^3.5.0 - Upgrade to
dart_style2.3.7. - Move to
dart-lang/toolsmonorepo.
- Require Dart
-
4.10.008 Jan 2024Release notes
Open source →- Add
Library.docsto support emitting doc comments on libraries. - Export
RepresentationDeclarationandRepresentationDeclarationBuilderso they can be used when generating extension types. - Upgrade to
dart_style2.3.4.
- Add
-
4.9.015 Dec 2023Release notes
Open source →- Add
Library.generatedByCommentto support emitting 'generated by' comments. - Support emitting an unnamed library with annotations.
- Add
-
4.8.020 Nov 2023Release notes
Open source →- Add
Expression.operatorSubtract - Deprecate
Expression.operatorSubstract - Add
Expression.operatorIntDivide - Add
Expression.operatorUnaryPrefixIncrement - Add
Expression.operatorUnaryPostfixIncrement - Add
Expression.operatorUnaryMinus - Add
Expression.operatorUnaryPrefixDecrement - Add
Expression.operatorUnaryPostfixDecrement - Add
Expression.operatorBitwiseAnd - Add
Expression.operatorBitwiseOr - Add
Expression.operatorBitwiseXor - Add
Expression.operatorUnaryBitwiseComplement - Add
Expression.operatorShiftLeft - Add
Expression.operatorShiftRight - Add
Expression.operatorShiftRightUnsigned - Add
Expression.addAssign - Add
Expression.subtractAssign - Add
Expression.multiplyAssign - Add
Expression.divideAssign - Add
Expression.intDivideAssign - Add
Expression.euclideanModuloAssign - Add
Expression.shiftLeftAssign - Add
Expression.shiftRightAssign - Add
Expression.shiftRightUnsignedAssign - Add
Expression.bitwiseAndAssign - Add
Expression.bitwiseXorAssign - Add
Expression.bitwiseOrAssign - Allow passing an
Expressionthroughliteralwithout an exception. - Add support for extension types.
- Update SDK version constraints to
>=3.0.0.
- Add
-
4.7.025 Sep 2023 -
4.6.030 Aug 2023Release notes
Open source →- Add support for named arguments in
enumclasses - Add support for external keyword on fields.
- Add
Expression.parenthesizedto manually wrap an expression in parenthesis.
- Add support for named arguments in
-
4.5.001 Jun 2023Release notes
Open source →- Require Dart 2.19
- Add support for emitting type parameters for typedefs.
- Add support for class modifiers.
- Add support for records (both types and record literals).
- Add
literalSpreadandliteralNullSafeSpreadto support adding spreads toliteralMap.
void main() { // Creates a map // { // ...one, // 2: two, // ...?three, // } final map = literalMap({ literalSpread(): refer('one'), 2: refer('two'), literalNullSafeSpread(): refer('three'), }); } -
4.4.020 Dec 2022Release notes
Open source →- Mention how the
allocatorargument relates to imports in theDartEmitterconstructor doc. - Add support for emitting typedefs.
- Add support for emitting leading line comments for libraries.
- Add support for emitting
ignore_for_fileanalyzer directive comments.
- Mention how the
-
4.3.014 Sep 2022Release notes
Open source →- Add support for adding more implementation in
enumclasses. - Only emit
latekeyword when using null safety syntax. - Use implicit
constwhen assigning to adeclareConstvariable. - Deprecate
assignVar,assignConst, andassignFinal. - Add trailing commas to any parameter list, argument list, or collection literal which has more than one element.
- Add support for adding more implementation in
-
4.2.027 Jul 2022Release notes
Open source →- Add an ignore for a lint from the
package:lintsrecommended set. The lint,no_leading_underscores_for_library_prefixesis most useful for hand edited code where the appearance of a private name that is already not visible outside the library is confusing. - Fix the docs for
Expression.assign,ifNullThen, andassignNullAwarewhich had the argument and receiver flipped. - Add
declareConst,declareFinal, anddeclareVarto replaceExpression.assignConst,assignFinal, andassignVar. Add support for late variables with thedeclare*utilities. - Add
ParameterBuilder.toSuperso support super formal parameters language feature.
- Add an ignore for a lint from the
-
4.1.020 Jul 2021Release notes
Open source →- Add
Expression.spreadfor the spread operator.... - Add support 'late' field modifier.
- Add support for
Expression.nullCheckedto add a null assertion operator. - Add support for creating
mixins. - Add
Expression.nullSafeSpreadfor the null aware spread operator...?. - A
Librarycan now be annotated.
- Add
-
4.0.019 Apr 2021Release notes
Open source →- Migrate to null safety.
- Changed the
DartEmitterconstructor to use named optional parameters. - Add
ParenthesizedExpressionandExpressionVisitor.visitParenthesizedExpression.
-
3.7.010 Mar 2021Release notes
Open source →- Add support for converting a Method to a generic closure, with
Method.genericClosure.
- Add support for converting a Method to a generic closure, with
-
3.6.013 Jan 2021Release notes
Open source →- Add support for creating
extensionmethods. - Expand constraint on
built_valueto allow null safe migrated version.
- Add support for creating
-
3.5.009 Oct 2020Release notes
Open source →- Add support for defining enums.
- Fix keyword ordering for
const factoryconstructors.
-
3.4.118 Aug 2020Release notes
Open source →- Fix confusing mismatch description from
equalsDart. https://github.com/dart-lang/code_builder/issues/293
- Fix confusing mismatch description from
-
3.4.008 Jul 2020Release notes
Open source →- Introduce
Expression.thrownfor throwing an expression. - Introduce
FunctionType.isNullable. - Update SDK requirement to
>=2.7.0 <3.0.0.
- Introduce
-
3.3.021 May 2020Release notes
Open source →- Add
??null-aware operator. - Add
..cascade assignment operator. - Add
partdirective. - Introduce
TypeReference.isNullable. - Add an option in
DartEmitterto emit nullable types with trailing?characters.
- Add
-
3.2.114 Nov 2019Release notes
Open source →- Escape newlines in String literals.
- Introduce
Expression.orfor boolean OR. - Introduce
Expression.negatefor boolean NOT. - No longer emits redundant
,s inFunctionTypes. - Added support for
literalSetandliteralConstSet. - Depend on the latest
package:built_value.
-
3.2.031 Jan 2019Release notes
Open source →- Emit
=instead of:for named parameter default values. - The
newkeyword will not be used in generated code. - The
constkeyword will be omitted when it can be inferred. - Add an option in
DartEmitterto order directives. DartEmitteradded astartConstCodefunction to track the creation of constant expression trees.BinaryExpressionadded thefinal bool isConstfield.
- Emit
-
3.1.330 Aug 2018 -
3.1.219 Jul 2018 -
3.1.126 Jun 2018Release notes
Open source →Expression.asAis now wrapped with parenthesis so that further calls may be made on it as an expression.
-
3.1.001 Jun 2018Release notes
Open source →- Added
Expression.asAfor creating explicit casts:
void main() { test('should emit an explicit cast', () { expect( refer('foo').asA(refer('String')), equalsDart('foo as String'), ); }); } - Added
-
3.0.310 Feb 2018Release notes
Open source →- Fix a bug that caused all downstream users of
code_builderto crash due tobuild_runnertrying to import our private builder (intool/). Sorry for the inconvenience.
- Fix a bug that caused all downstream users of
-
3.0.210 Feb 2018 -
3.0.130 Jan 2018Release notes
Open source →- Upgrade to
built_value5.1.0. - Export the
literalNumfunction. - BUG FIX:
literalsupports aMap.
- Upgrade to
-
3.0.009 Jan 2018Release notes
Open source →- Adds discovery API to find both a configuration and its location:
findPackageConfigAndFileandfindPackageConfigAndUri. - Removes support for the
.packagesfile.
The Dart SDK no longer supports that file, and no new.packagesfiles
will be generated.
Since the SDK requirement for this package is above 3.0.0,
no supporting SDK can use or generate.packages. - Simplifies API that no longer needs to support two separate files.
- Renamed
readAnyConfigFiletoreadConfigFile, and removed
thepreferNewestparameter. - Same for
readAnyConfigFileUriwhich becomesreadConfigFileUri. - Old functions still exists as deprecated, forwarding to the new
functions without thepreferNewestargument.
MakesPackageConfig,PackageandLanguageVersion@sealedclasses,
in preparation for making themfinalin a future update.
- Renamed
- Adds
PackageConfig.minVersionto complement.maxVersion.
Currently both are2.
- Adds discovery API to find both a configuration and its location:
-
3.0.0-alpha22 Dec 2017 pre-releaseRelease notes
Open source →-
Using
equalsDartno longer formats automatically withdartfmt. -
Removed deprecated
AnnotationandFileclasses. -
Method.lambdais inferred based onMethod.bodywhere possible and now defaults tonull.
-
-
2.4.011 Dec 2017Release notes
Open source →- Add
equalTo,notEqualTo,greaterThan,lessThan,greaterOrEqualTo, andlessOrEqualTotoExpression.
- Add
-
2.3.027 Nov 2017Release notes
Open source →- Using
equalsDartand expectingdartfmtby default is deprecated. This requires this package to have a direct dependency on specific versions ofdart_style(and transitivelyanalyzer), which is problematic just for testing infrastructure. To future proof, we've exposed theEqualsDartclass with aformatoverride:
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:code_builder/code_builder.dart'; import 'package:dart_style/dart_style.dart'; final DartFormatter _dartfmt = new DartFormatter(); String _format(String source) { try { return _dartfmt.format(source); } on FormatException catch (_) { return _dartfmt.formatStatement(source); } } /// Should be invoked in `main()` of every test in `test/**_test.dart`. void useDartfmt() => EqualsDart.format = _format;- Added
Expression.isAandExpression.isNotA:
void main() { test('should emit an is check', () { expect( refer('foo').isA(refer('String')), equalsDart('foo is String'), ); }); }- Deprecated
Annotation. It is now legal to simply pass anyExpressionas a metadata annotation toClass,Method,Field,andParameter. In3.0.0, theAnnotationclass will be completely removed:
void main() { test('should create a class with a annotated constructor', () { expect( new Class((b) => b ..name = 'Foo' ..constructors.add( new Constructor((b) => b..annotations.add(refer('deprecated'))))), equalsDart(r''' class Foo { @deprecated Foo(); } '''), ); }); }- Added inference support for
Method.lambdaandConstructor.lambda. If not explicitly provided and the body of the function originated from anExpressionthenlambdais inferred to be true. This is not a breaking change yet, as it requires an explicitnullvalue. In3.0.0this will be the default:
void main() { final animal = new Class((b) => b ..name = 'Animal' ..extend = refer('Organism') ..methods.add(new Method.returnsVoid((b) => b ..name = 'eat' // In 3.0.0, this may be omitted and still is inferred. ..lambda = null ..body = refer('print').call([literalString('Yum!')]).code))); final emitter = new DartEmitter(); print(new DartFormatter().format('${animal.accept(emitter)}')); }- Added
nullSafePropertytoExpressionto access properties with?. - Added
conditionaltoExpressionto use the ternary operator? : - Methods taking
positionalArgumentsacceptIterable<Expression> - BUG FIX: Parameters can take a
FunctionTypeas atype.Reference.typenow returns aReference. Note that this change is technically breaking but should not impacts most clients.
- Using
-
2.2.022 Nov 2017Release notes
Open source →-
Imports are prefixed with
_i1rather than_1which satisfies the lintlowercase_with_underscores. While not a strictly breaking change you may have to fix/regenerate golden file-like tests. We added documentation that the specific prefix is not considered stable. -
Added
Expression.indexfor accessing the[]operator:
void main() { test('should emit an index operator', () { expect( refer('bar').index(literalTrue).assignVar('foo').statement, equalsDart('var foo = bar[true];'), ); }); test('should emit an index operator set', () { expect( refer('bar') .index(literalTrue) .assign(literalFalse) .assignVar('foo') .statement, equalsDart('var foo = bar[true] = false;'), ); }); }-
literalListaccepts anIterableargument. -
Fixed an NPE when a method had a return type of a
FunctionType:
void main() { test('should create a method with a function type return type', () { expect( new Method((b) => b ..name = 'foo' ..returns = new FunctionType((b) => b ..returnType = refer('String') ..requiredParameters.addAll([ refer('int'), ]))), equalsDart(r''' String Function(int) foo(); '''), ); }); } -
-
2.1.004 Nov 2017Release notes
Open source →We now require the Dart 2.0-dev branch SDK (
>= 2.0.0-dev).- Added support for raw
Stringliterals. - Automatically escapes single quotes in now-raw
Stringliterals. - Deprecated
File, which is now a redirect to the preferred class,Library.
This helps avoid symbol clashes when used with
dart:io, a popular library. It is now safe to do the following and get full access to thecode_builderAPI:import 'dart:io'; import 'package:code_builder/code_builder.dart' hide File;We will remove
Filein3.0.0, so useLibraryinstead. - Added support for raw
-
2.1.0-dev04 Nov 2017 pre-releaseNothing published for this version
-
2.0.028 Oct 2017Release notes
Open source →Re-released without a direct dependency on
package:analyzer!For users of the
1.xbranch ofcode_builder, this is a pretty big breaking change but ultimately is for the better - it's easier to evolve this library now and even add your own builders on top of the library.// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:code_builder/code_builder.dart'; import 'package:dart_style/dart_style.dart'; void main() { final animal = new Class((b) => b ..name = 'Animal' ..extend = refer('Organism') ..methods.add(new Method.returnsVoid((b) => b ..name = 'eat' ..lambda = true ..body = const Code('print(\'Yum\')')))); final emitter = new DartEmitter(); print(new DartFormatter().format('${animal.accept(emitter)}')); }...outputs...
class Animal extends Organism { void eat() => print('Yum!'); }Major changes:
- Builders now use
built_value, and have a more consistent, friendly API. - Builders are now consistent - they don't perform work work until code is emitted.
- It's possible to overwrite the built-in code emitting, formatting, etc by
providing your own visitors. See
DartEmitteras an example of the built-in visitor/emitter. - Most of the expression and statement-level helpers were removed; in practice,
they were difficult to write and maintain, and many users commonly asked for
opt-out type APIs. See the
Codeexample below:
void main() { var code = new Code('x + y = z'); code.expression; code.statement; }See the commit log, examples, and tests for full details. While we want to try and avoid breaking changes, suggestions, new features, and incremental updates are welcome!
- Builders now use
-
2.0.0-beta24 Oct 2017 pre-release -
2.0.0-alpha14 Jul 2017 pre-releaseRelease notes
Open source →- Complete re-write to not use
package:analyzer. - Code generation now properly uses the builder pattern (via
built_value). - See examples and tests for details.
- Complete re-write to not use
-
2.0.0-alpha+114 Jul 2017 pre-releaseRelease notes
Open source →- Removed
Reference.localScope. Just useReference(symbol)now. - Allow
Referenceinstead of an explicitTypeReferencein most APIs.toType()is performed for you as part the emitter process
final animal = new Class((b) => b ..name = 'Animal' // Used to need a suffix of .toType(). ..extend = const Reference('Organism') ..methods.add(new Method.returnsVoid((b) => b ..name = 'eat' ..lambda = true ..body = new Code((b) => b..code = 'print(\'Yum\')'))));- We now support the Dart 2.0 pre-release SDKs (
<2.0.0-dev.infinity) - Removed the ability to treat
Classas aTypeReference.- Was required for compilation to
dart2js, which is now tested on travis.
- Was required for compilation to
- Removed
-
2.0.0-alpha+213 Oct 2017 pre-releaseRelease notes
Open source →-
Upgraded
build_runnerfrom^0.3.0to>=0.4.0 <0.6.0. -
Upgraded
build_value{_generator}from^1.0.0to>=2.0.0 <5.0.0. -
Upgraded
source_genfrom>=0.5.0 <0.7.0to^0.7.0. -
Added
MethodModifierto allow emit aMethodwithasync|async*|sync*. -
Added
show|hidetoDirective. -
Added
Directive.importDeferredAs. -
Added a new line character after emitting some types (class, method, etc).
-
Added
referas a short-hand fornew Reference(...).Referencenow implementsExpression.
-
Added many classes/methods for writing bodies of
Codefluently:ExpressionLiteralExpressionliteralliteralNullliteralBoolliteralTrueliteralFalseliteralNumliteralStringliteralListandliteralConstListliteralMapandliteralConstMap
const Code(staticString)const Code.scope((allocate) => '')
-
Removed
SimpleSpecVisitor(it was unused). -
Removed
implements ReferencefromMethodandField; not a lot of value. -
SpecVisitor<T>'s methods all have an optional[T context]parameter now.- This makes it much easier to avoid allocating extra
StringBuffers.
- This makes it much easier to avoid allocating extra
-
equalsDartremoves insignificant white space before comparing results.
-
-
2.0.0-alpha+316 Oct 2017 pre-releaseRelease notes
Open source →-
Added
Expression.annotationandExpression.annotationNamed. -
Added
Method.closureto create anExpression. -
Added
FunctionType. -
Added
{new|const}InstanceNamedtoExpression#135.- Also added a
typeArgumentsoption to all invocations.
- Also added a
-
Added
assign{...}variants toExpression#137. -
Added
.awaitedand.returnedtoExpression#138. -
BUG FIX:
Blocknow implementsCode#136. -
BUG FIX:
new DartEmitter.scoped()applies prefixing #139. -
Renamed many of the
.asFoo(...)and.toFoo(...)methods to single getter:asCode()tocodeasStatement()tostatementtoExpression()toexpression
-
Moved
{new|const}Instance{[Named]}fromExpressiontoReference.
-
-
1.0.416 Jun 2017Release notes
Open source →- Added
isInstanceOftoExpressionBuilder, which performs anischeck:
expect( reference('foo').isInstanceOf(_barType), equalsSource('foo is Bar'), ); - Added
-
1.0.312 May 2017 -
1.0.202 May 2017 -
1.0.105 Apr 2017 -
1.0.031 Mar 2017Release notes
Open source →First full release. At this point, all changes until
2.0.0will be backward compatible (new features) or bug fixes that are not breaking. This doesn't mean that the entire Dart language is buildable with our API, though.Contributions are welcome.
- Exposed
uriinImportBuilder,ExportBuilder, andPart[Of]Builder.
- Exposed
-
1.0.0-beta05 Jan 2017 pre-releaseRelease notes
Open source →- Add support for
async,sync,sync*functions - Add support for expression
asAwait,asYield,asYieldStar - Add
toExportBuilderandtoImportBuilderto types and references - Fix an import scoping bug in
returnstatements and named constructor invocations. - Added constructor initializer support
- Add
whileanddo {} whileloop support - Add
forandfor-insupport - Added a
namegetter forParameterBuilder
- Add support for
-
1.0.0-beta+112 Jan 2017 pre-releaseRelease notes
Open source →- Add support for
switchstatements - Add support for a raw expression and statement
new ExpressionBuilder.raw(...)new StatementBuilder.raw(...)
This should help cover any cases not covered with builders today.
- Allow referring to a
ClassBuilderandTypeBuilderas an expression - Add support for accessing the index
[]operator on an expression
BREAKING CHANGES
- Changed
ExpressionBuilder.asAssignto always take anExpressionBuilderas target and removed thevalueproperty. Most changes are pretty simple, and involve just usingreference(...). For example:
literal(true).asAssign(reference('flag'))... emits
flag = true. - Add support for
-
1.0.0-beta+331 Jan 2017 pre-releaseRelease notes
Open source →- Added support for
genericTypesparameter forExpressionBuilder#invoke:
expect( explicitThis.invoke('doThing', [literal(true)], genericTypes: [ lib$core.bool, ]), equalsSource(r''' this.doThing<bool>(true) '''), );- Added a
castAsmethod toExpressionBuilder:
expect( literal(1.0).castAs(lib$core.num), equalsSource(r''' 1.0 as num '''), );BREAKING CHANGES
- Removed
namedNewInstanceandnamedConstInstance, replaced withconstructor::
expect( reference('Foo').newInstance([], constructor: 'other'), equalsSource(r''' new Foo.other() '''), );- Renamed
namedparameter tonamedArguments:
expect( reference('doThing').call( [literal(true)], namedArguments: { 'otherFlag': literal(false), }, ), equalsSource(r''' doThing(true, otherFlag: false) '''), ); - Added support for
-
1.0.0-beta+401 Mar 2017 pre-releaseRelease notes
Open source →- Renamed
PartBuildertoPartOfBuilder. - Added a new class,
PartBuilder, to representpart '...dart'directives. - Added the
HasAnnotationsinterface to all library/part/directive builders. - Added
asFactoryandasConsttoConstructorBuilder. - Added
ConstructorBuilder.redirectTofor a redirecting factory constructor. - Added a
namegetter toReferenceBuilder. - Supplying an empty constructor name (
'') is equivalent tonull(default). - Automatically encodes string literals with multiple lines as
'''. - Added
asThrowtoExpressionBuilder. - Fixed a bug that prevented
FieldBuilderfrom being used at the top-level.
- Renamed
-
1.0.0-beta+502 Mar 2017 pre-release -
1.0.0-beta+616 Mar 2017 pre-releaseRelease notes
Open source →- Added
TypeDefBuilder. - Added
FunctionParameterBuilder. - Added
asAbstractto variousMethodBuilderconstructors.
- Added
-
1.0.0-beta+729 Mar 2017 pre-release -
1.0.0-alpha15 Nov 2016 pre-release -
1.0.0-alpha+216 Nov 2016 pre-releaseRelease notes
Open source →- Added
returnVoidto well,return; - Added support for top-level field assignments:
new LibraryBuilder()..addMember(literal(false).asConst('foo'))- Added support for specifying a
targetwhen usingasAssign:
// Outputs bank.bar = goldBar reference('goldBar').asAssign('bar', target: reference('bank'))- Added support for the cascade operator:
// Outputs foo..doThis()..doThat() reference('foo').cascade((c) => <ExpressionBuilder> [ c.invoke('doThis', []), c.invoke('doThat', []), ]);- Added support for accessing a property
// foo.bar reference('foo').property('bar'); - Added
-
1.0.0-alpha+421 Nov 2016 pre-release -
1.0.0-alpha+522 Nov 2016 pre-releaseRelease notes
Open source →- MethodBuilder with no statements will create an empty block instead of a semicolon.
// main() {} method('main')- Fix lambdas and closures to not include a trailing semicolon when used as an expression.
// () => false new MethodBuilder.closure(returns: literal(false)); -
1.0.0-alpha+622 Nov 2016 pre-release -
1.0.0-alpha+729 Nov 2016 pre-releaseRelease notes
Open source →- Make use of the new analyzer APIs in preparation for analyzer version 0.30.