code_builder 2.0.0-alpha+1 copy "code_builder: ^2.0.0-alpha+1" to clipboard
code_builder: ^2.0.0-alpha+1 copied to clipboard

outdatedDart 1 only

A fluent API for generating Dart code

code_builder #

pub package Build Status Coverage Status

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

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.

Usage #

code_builder has a narrow and user-friendly API.

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 = const Reference('Organism').toType()
    ..methods.add(new Method.returnsVoid((b) => b
      ..name = 'eat'
      ..lambda = true
      ..body = new Code((b) => b..code = 'print(\'Yum\')'))));
  final emitter = const 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 File((b) => b.body.addAll([
        new Method((b) => b
          ..body = new Code((b) => b.code = '')
          ..name = 'doThing'
          ..returns = const Reference('Thing', 'package:a/a.dart')),
        new Method((b) => b
          ..body = new Code((b) => b..code = '')
          ..name = 'doOther'
          ..returns = const Reference('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 _1;
import 'package:b/b.dart' as _2;

_1.Thing doThing() {}
_2.Other doOther() {}