stateOf<T> method

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

Retrieves or lazily creates a state of type T, and binds its ValueNotifier lifecycle to this BuildContext's widget lifecycle.

onDispose is called with the current value when the state is removed from its scope and disposed.

Implementation

ValueNotifier<T> stateOf<T>(
  T Function() create, {
  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 id = StateId(key: key, type: T);
  return element.ensureState<T>(this as Element, id, mode, create, onDispose);
}