of static method

OverlayState of(
  1. BuildContext context, {
  2. bool rootOverlay = false,
  3. Widget? debugRequiredFor,
})

The OverlayState from the closest instance of Overlay that encloses the given context within the closest LookupBoundary, and, in debug mode, will throw if one is not found.

In debug mode, if the debugRequiredFor argument is provided and an overlay isn't found, then this function will throw an exception containing the runtime type of the given widget in the error message. The exception attempts to explain that the calling Widget (the one given by the debugRequiredFor argument) needs an Overlay to be present to function. If debugRequiredFor is not supplied, then the error message is more generic.

Typical usage is as follows:

OverlayState overlay = Overlay.of(context);

If rootOverlay is set to true, the state from the furthest instance of this class is given instead. Useful for installing overlay entries above all subsequent instances of Overlay.

This method can be expensive (it walks the element tree).

See also:

Implementation

static OverlayState of(
  BuildContext context, {
  bool rootOverlay = false,
  Widget? debugRequiredFor,
}) {
  final OverlayState? result = maybeOf(context, rootOverlay: rootOverlay);
  assert(() {
    if (result == null) {
      final bool hiddenByBoundary = LookupBoundary.debugIsHidingAncestorStateOfType<OverlayState>(context);
      final List<DiagnosticsNode> information = <DiagnosticsNode>[
        ErrorSummary('No Overlay widget found${hiddenByBoundary ? ' within the closest LookupBoundary' : ''}.'),
        if (hiddenByBoundary)
          ErrorDescription(
              'There is an ancestor Overlay widget, but it is hidden by a LookupBoundary.'
          ),
        ErrorDescription('${debugRequiredFor?.runtimeType ?? 'Some'} widgets require an Overlay widget ancestor for correct operation.'),
        ErrorHint('The most common way to add an Overlay to an application is to include a MaterialApp, CupertinoApp or Navigator widget in the runApp() call.'),
        if (debugRequiredFor != null) DiagnosticsProperty<Widget>('The specific widget that failed to find an overlay was', debugRequiredFor, style: DiagnosticsTreeStyle.errorProperty),
        if (context.widget != debugRequiredFor)
          context.describeElement('The context from which that widget was searching for an overlay was'),
      ];

      throw FlutterError.fromParts(information);
    }
    return true;
  }());
  return result!;
}