code_builder 3.0.0-alpha copy "code_builder: ^3.0.0-alpha" to clipboard
code_builder: ^3.0.0-alpha copied to clipboard

outdatedDart 1 only

A fluent API for generating Dart code

code_builder #

Pub package Build status Latest docs Gitter 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';

void main() {
  final animal = new Class((b) => b
    ..name = 'Animal'
    ..extend = refer('Organism')
    ..methods.add(new Method.returnsVoid((b) => b
      ..name = 'eat'
      ..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!');
}

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';

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

Outputs:

import 'package:a/a.dart' as _i1;
import 'package:b/b.dart' as _i2;

_i1.Thing doThing() {}
_i2.Other doOther() {}

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 .
229
likes
0
points
3.18M
downloads

Publisher

verified publishertools.dart.dev

Weekly Downloads

A fluent API for generating Dart code

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

built_collection, built_value, matcher, meta

More

Packages that depend on code_builder