ProviderContainer constructor

ProviderContainer({
  1. ProviderContainer? parent,
  2. List<Override> overrides = const [],
  3. List<ProviderObserver>? observers,
  4. @internal void onError(
    1. Object error,
    2. StackTrace stackTrace
    )?,
  5. Retry? retry,
})

An object that stores the state of the providers and allows overriding the behavior of a specific provider.

If you are using Flutter, you do not need to care about this object (outside of testing), as it is implicitly created for you by ProviderScope.

Inside tests, consider using ProviderContainer.test. This will automatically dispose the container at the end of the test.

Implementation

ProviderContainer({
  ProviderContainer? parent,
  List<Override> overrides = const [],
  List<ProviderObserver>? observers,
  @internal void Function(Object error, StackTrace stackTrace)? onError,
  Retry? retry,
}) : _debugOverridesLength = overrides.length,
     _depth = parent == null ? 0 : parent._depth + 1,
     _parent = parent,
     _onError = onError ?? Zone.current.handleUncaughtError,
     retry = retry ?? parent?.retry,
     observers = [...?observers, if (parent != null) ...parent.observers],
     _root = parent?._root ?? parent {
  if (parent != null) {
    if (parent.disposed) {
      throw StateError(
        'Cannot create a ProviderContainer that has a disposed parent',
      );
    }
  }

  if (kDebugMode) {
    final overrideOrigins = <Object?>{};
    for (final override in overrides) {
      switch (override) {
        case _ProviderOverride():
          if (!overrideOrigins.add(override.origin)) {
            throw AssertionError(
              'Tried to override a provider twice within the same container: ${override.origin}',
            );
          }
        case _FamilyOverride():
          if (!overrideOrigins.add(override.from)) {
            throw AssertionError(
              'Tried to override a family twice within the same container: ${override.from}',
            );
          }
      }
    }
  }

  _pointerManager =
      parent != null
          ? ProviderPointerManager.from(parent, overrides, container: this)
          : ProviderPointerManager(
            overrides,
            container: this,
            orphanPointers: ProviderDirectory.empty(
              this,
              familyOverride: null,
            ),
          );

  // Mutate the parent & global state only at the very end.
  // This ensures that if an error is thrown, the parent & global state
  // are not affected.
  parent?._children.add(this);
}