capture method

String capture(
  1. int indentLevel,
  2. void f()
)

Redirects subsequent code generation into a temporary buffer.

Keeps the original buffer intact, applies the temporary indentLevel, executes f, and returns the captured source code string.

Implementation

String capture(int indentLevel, void Function() f) {
  final originalBuffer = _buffer;
  final originalIndent = _indentLevel;
  _buffer = StringBuffer();
  _indentLevel = indentLevel;
  try {
    f();
    final source = _buffer.toString().trimRight();
    return source;
  } finally {
    _buffer = originalBuffer;
    _indentLevel = originalIndent;
  }
}