withRegistrations<T> static method

T withRegistrations<T>(
  1. Iterable<ChartRegistration> registrations,
  2. T body(), {
  3. bool clearBefore = false,
})

Temporarily registers registrations while synchronous body runs, then restores the previous registry state even when body throws.

Use withRegistrationsAsync for async work. Passing a Future-returning body here is rejected because the registry would otherwise restore before the async work completes.

Implementation

static T withRegistrations<T>(
  Iterable<ChartRegistration> registrations,
  T Function() body, {
  bool clearBefore = false,
}) {
  final previous = snapshot();
  try {
    if (clearBefore) clear();
    registerAll(registrations);
    final result = body();
    if (result is Future) {
      throw StateError(
        'ChartRegistry.withRegistrations() received an async body. '
        'Use ChartRegistry.withRegistrationsAsync() for Future-returning '
        'work so temporary registrations remain active until completion.',
      );
    }
    return result;
  } finally {
    restore(previous);
  }
}