sharedStateOf<T> method

ValueNotifier<T> sharedStateOf<T>(
  1. T create(), {
  2. required Key key,
  3. StateMode mode = StateMode.watch,
  4. dynamic onDispose(
    1. T
    )?,
})

Retrieves or lazily creates state shared by key across elements under the same StateScope.

onDispose is called with the current value when the last dependent element is removed and the shared state is disposed.

Implementation

ValueNotifier<T> sharedStateOf<T>(
  T Function() create, {
  required Key key,
  StateMode mode = StateMode.watch,
  Function(T)? onDispose,
}) {
  final element = getElementForInheritedWidgetOfExactType<StateScope>();

  if (element is! StateScopeElement) {
    throw FlutterError(
      'StateScope was not found above this BuildContext.\n'
      'Place StateScope above this context or use ServiceScope.withState.',
    );
  }

  final dependent = this as Element;
  final id = StateId(element: null, key: key, type: T);
  return element.ensureState<T>(dependent, id, mode, create, onDispose);
}