serviceOf<T extends Service> method

T serviceOf<T extends Service>(
  1. T create(), {
  2. Key? key,
  3. ServiceMode mode = ServiceMode.watch,
})

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

Implementation

T serviceOf<T extends Service>(
  T Function() create, {
  Key? key,
  ServiceMode mode = ServiceMode.watch,
}) {
  final element = getElementForInheritedWidgetOfExactType<ServiceScope>();

  if (element is! ServiceScopeElement) {
    throw FlutterError(
      'ServiceScope was not found above this BuildContext.\n'
      'Please ensure ServiceScope is placed near the root of your widget tree.',
    );
  }

  final id = ServiceId(key: key, type: T);
  return element.ensureService<T>(this as Element, id, mode, create);
}