CodeBlanks Logo Icon CodeBlanks

Builder

Learn code generators with Builder.

Builder

Builder is the code generator interface that build_runner runs. The build(BuildStep) method reads source files and writes generated files.

A Builder declares: buildExtensions (input → output map, e.g. '.dart' → '.g.dart') and the build method itself.

The BuildStep context provides file reading/writing, dependency resolution and logging. Builders are stateless; they are recreated on each build.

The buildExtensions map

buildExtensions maps input extension to output extension: {'.dart': '.g.dart'}. build_runner uses this map to know which files to generate.

A Builder can produce multiple outputs: {'.dart': ['.g.dart', '.freezed.dart']}. Each output is a separate file.

When writing a Builder, you first define buildExtensions, then the build method. Together they form the generation contract.

Practice Define a Builder skeleton

Define a Builder class with String get outputExtension => '.g.dart'; and String build(String input) => '// generated from $input'; methods. In main create final builder = Builder();; print builder.outputExtension and builder.build('user.dart').

Starter code

main.dart
void main() {
  // define a Builder class (outputExtension getter, build method)
  // create a Builder; print outputExtension and build('user.dart')
}

Sample solution

main.dart
class Builder {
  String get outputExtension => '.g.dart';
  String build(String input) => '// generated from $input';
}

void main() {
  final builder = Builder();
  print(builder.outputExtension);
  print(builder.build('user.dart'));
}

Expected output

.g.dart
// generated from user.dart

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 The build method

Question
Future<void> ____(BuildStep step) async {
  // read source, write output
}
Answer
Future<void> build(BuildStep step) async {
  // read source, write output
}

Explanation: the build(BuildStep) method does the generation.

2 Which method does a Builder implement?

  • compile(Library)
  • generate(String)
  • build(BuildStep) Correct answer
  • run(Builder)

Explanation: a Builder implements the build(BuildStep) method.

3 Match the Builder parts

Term Meaning
build(BuildStep) Build method
BuildStep Input context
buildExtensions Extension map
Future<void> Return type

All lessons in Expert