debugCheckHasMaterialLocalizations function Null safety

bool debugCheckHasMaterialLocalizations(
  1. BuildContext context
)

Asserts that the given context has a Localizations ancestor that contains a MaterialLocalizations delegate.

Used by many Material Design widgets to make sure that they are only used in contexts where they have access to localizations.

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

assert(debugCheckHasMaterialLocalizations(context));

This function has the side-effect of establishing an inheritance relationship with the nearest Localizations widget (see BuildContext.dependOnInheritedWidgetOfExactType). This is ok if the caller always also calls Localizations.of or Localizations.localeOf.

Does nothing if asserts are disabled. Always returns true.

Implementation

bool debugCheckHasMaterialLocalizations(BuildContext context) {
  assert(() {
    if (Localizations.of<MaterialLocalizations>(context, MaterialLocalizations) == null) {
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('No MaterialLocalizations found.'),
        ErrorDescription(
          '${context.widget.runtimeType} widgets require MaterialLocalizations '
          'to be provided by a Localizations widget ancestor.',
        ),
        ErrorDescription(
          'The material library uses Localizations to generate messages, '
          'labels, and abbreviations.',
        ),
        ErrorHint(
          'To introduce a MaterialLocalizations, either use a '
          'MaterialApp at the root of your application to include them '
          'automatically, or add a Localization widget with a '
          'MaterialLocalizations delegate.',
        ),
        ...context.describeMissingAncestor(expectedAncestorType: MaterialLocalizations),
      ]);
    }
    return true;
  }());
  return true;
}