debugCheckHasMaterialLocalizations function
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));
Does nothing if asserts are disabled. Always returns true.
Implementation
bool debugCheckHasMaterialLocalizations(BuildContext context) {
assert(() {
if (Localizations.of<MaterialLocalizations>(context, MaterialLocalizations) == null) {
final StringBuffer message = StringBuffer();
message.writeln('No MaterialLocalizations found.');
message.writeln(
'${context.widget.runtimeType} widgets require MaterialLocalizations '
'to be provided by a Localizations widget ancestor.'
);
message.writeln(
'Localizations are used to generate many different messages, labels,'
'and abbreviations which are used by the material library. '
);
message.writeln(
'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.'
);
message.writeln(
'The specific widget that could not find a MaterialLocalizations ancestor was:'
);
message.writeln(' ${context.widget}');
final List<Widget> ancestors = <Widget>[];
context.visitAncestorElements((Element element) {
ancestors.add(element.widget);
return true;
});
if (ancestors.isNotEmpty) {
message.write('The ancestors of this widget were:');
for (Widget ancestor in ancestors)
message.write('\n $ancestor');
} else {
message.writeln(
'This widget is the root of the tree, so it has no '
'ancestors, let alone a "Localizations" ancestor.'
);
}
throw FlutterError(message.toString());
}
return true;
}());
return true;
}