of method Null safety

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

The state from the closest instance of this class that encloses the given context.

In debug mode, if the debugRequiredFor argument is provided then this function will assert that an overlay was found and will throw an exception if not. The exception attempts to explain that the calling Widget (the one given by the debugRequiredFor argument) needs an Overlay to be present to function.

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).

Implementation

static OverlayState? of(
  BuildContext context, {
  bool rootOverlay = false,
  Widget? debugRequiredFor,
}) {
  final OverlayState? result = rootOverlay
      ? context.findRootAncestorStateOfType<OverlayState>()
      : context.findAncestorStateOfType<OverlayState>();
  assert(() {
    if (debugRequiredFor != null && result == null) {
      final List<DiagnosticsNode> information = <DiagnosticsNode>[
        ErrorSummary('No Overlay widget found.'),
        ErrorDescription('${debugRequiredFor.runtimeType} 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 or Navigator widget in the runApp() call.'),
        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;
}