Skip to content

Repository files navigation

code_builder

Pub packageBuild statusLatest docsGitter chat

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

Usage

code_builder has a narrow and user-friendly API.

See the example and test folders for additional examples.

For example creating a class with a method:

import'package:code_builder/code_builder.dart';
import'package:dart_style/dart_style.dart';
voidmain() {
final animal =Class((b) => b
..name ='Animal'
..extend =refer('Organism')
..methods.add(Method.returnsVoid((b) => b
..name ='eat'
..body =constCode('print(\'Yum\')'))));
final emitter =DartEmitter();
print(DartFormatter().format('${animal.accept(emitter)}'));
}

Outputs:

classAnimalextendsOrganism {
voideat() =>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:

import'package:code_builder/code_builder.dart';
import'package:dart_style/dart_style.dart';
voidmain() {
final library =Library((b) => b.body.addAll([
Method((b) => b
..body =constCode('')
..name ='doThing'
..returns =refer('Thing', 'package:a/a.dart')),
Method((b) => b
..body =constCode('')
..name ='doOther'
..returns =refer('Other', 'package:b/b.dart')),
]));
final emitter =DartEmitter(Allocator.simplePrefixing());
print(DartFormatter().format('${library.accept(emitter)}'));
}

Outputs:

import'package:a/a.dart'as _i1;
import'package:b/b.dart'as _i2;
_i1.ThingdoThing() {}
_i2.OtherdoOther() {}

Contributing

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.

NOTE: Due to the evolving Dart SDK the local dartfmt must be used to format this repository. You can run it simply from the command-line:

$ pub run dart_style:format -w .

Updating generated (.g.dart) files

NOTE: There is currently a limitation in build_runner that requires a workaround for developing this package. We expect this to be unnecessary in the future.

Use build_runner:

$ mv build.disabled.yaml build.yaml
$ pub run build_runner build --delete-conflicting-outputs
$ mv build.yaml build.disabled.yaml

About

A fluent API for generating valid Dart source code

Resources

Contributing

Stars

0 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages