debugCheckHasMediaQuery function Null safety

bool debugCheckHasMediaQuery(
  1. BuildContext context

Asserts that the given context has a MediaQuery 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:


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.

Does nothing if asserts are disabled. Always returns true.


bool debugCheckHasMediaQuery(BuildContext context) {
  assert(() {
    if (context.widget is! MediaQuery && context.getElementForInheritedWidgetOfExactType<MediaQuery>() == null) {
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('No MediaQuery widget ancestor found.'),
        ErrorDescription('${context.widget.runtimeType} widgets require a MediaQuery widget ancestor.'),
        context.describeWidget('The specific widget that could not find a MediaQuery ancestor was'),
        context.describeOwnershipChain('The ownership chain for the affected widget is'),
          'No MediaQuery ancestor could be found starting from the context '
          'that was passed to MediaQuery.of(). This can happen because you '
          'have not added a WidgetsApp, CupertinoApp, or MaterialApp widget '
          '(those widgets introduce a MediaQuery), or it can happen if the '
          'context you use comes from a widget above those widgets.',
    return true;
  return true;