localeOf method Null safety

Locale localeOf(
  1. BuildContext context

The locale of the Localizations widget for the widget tree that corresponds to BuildContext context.

If no Localizations widget is in scope then the Localizations.localeOf method will throw an exception.


static Locale localeOf(BuildContext context) {
  assert(context != null);
  final _LocalizationsScope? scope = context.dependOnInheritedWidgetOfExactType<_LocalizationsScope>();
  assert(() {
    if (scope == null) {
      throw FlutterError(
        'Requested the Locale of a context that does not include a Localizations ancestor.\n'
        'To request the Locale, the context used to retrieve the Localizations widget must '
        'be that of a widget that is a descendant of a Localizations widget.',
    if (scope.localizationsState.locale == null) {
      throw FlutterError(
        'Localizations.localeOf found a Localizations widget that had a unexpected null locale.\n',
    return true;
  return scope!.localizationsState.locale!;