debugCheckHasScaffold function

bool debugCheckHasScaffold(
  1. BuildContext context
)

Asserts that the given context has a Scaffold ancestor.

Used by various widgets to make sure that they are only used in an appropriate context.

To invoke this function, use the following pattern, typically in the relevant Widget's build method:

assert(debugCheckHasScaffold(context));

Always place this before any early returns, so that the invariant is checked in all cases. This prevents bugs from hiding until a particular codepath is hit.

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

Does nothing if asserts are disabled. Always returns true.

Implementation

bool debugCheckHasScaffold(BuildContext context) {
  assert(() {
    if (context.widget is! Scaffold && context.findAncestorWidgetOfExactType<Scaffold>() == null) {
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('No Scaffold widget found.'),
        ErrorDescription('${context.widget.runtimeType} widgets require a Scaffold widget ancestor.'),
        ...context.describeMissingAncestor(expectedAncestorType: Scaffold),
        ErrorHint(
          'Typically, the Scaffold widget is introduced by the MaterialApp or '
          'WidgetsApp widget at the top of your application widget tree.',
        ),
      ]);
    }
    return true;
  }());
  return true;
}