attachDebugConsole function

void Function() attachDebugConsole([
  1. AttachDebugConsoleOptions options = const AttachDebugConsoleOptions()
])

Gắn logger vào debugBus. Trả về hàm gỡ.

Idempotent — gọi lại sẽ gỡ logger cũ trước, nên hot-reload hoặc widget rebuild hai lần không làm log nhân đôi.

Implementation

void Function() attachDebugConsole([
  AttachDebugConsoleOptions options = const AttachDebugConsoleOptions(),
]) {
  detachDebugConsole();

  if (options.autoEnable) debugBus.enabled = true;
  final print = options.printer ?? debugPrint;
  const encoder = JsonEncoder.withIndent('  ');

  final unsubscribe = debugBus.subscribe((event) {
    final summary = describeEvent(event);
    if (options.include != null && !options.include!.contains(summary.group)) {
      return;
    }

    final indent = '  ' * _depthOf(event);
    final marker = switch (summary.status) {
      DebugStatus.error => ' ⛔',
      DebugStatus.warn => ' ⚠️',
      _ => '',
    };
    print('${options.prefix} $indent${summary.label}$marker');

    if (!options.payloads) return;
    for (final payload in payloadsOf(event)) {
      if (payload.data == null) continue;
      final rendered = payload.data is String
          ? payload.data as String
          : _tryEncode(encoder, payload.data);
      print('${options.prefix} $indent    ${payload.label}: $rendered');
    }
  });

  _detachCurrent = () {
    unsubscribe();
    _detachCurrent = null;
  };
  return _detachCurrent!;
}