@@ -416,14 +416,38 @@ class Localizations extends StatefulWidget {
416416 /// true, in which case it returns null.
417417 static Locale ? localeOf (BuildContext context, { bool nullOk = false }) {
418418 assert (context != null );
419- assert (nullOk != null );
420419 final _LocalizationsScope ? scope = context.dependOnInheritedWidgetOfExactType <_LocalizationsScope >();
421420 if (nullOk && scope == null )
422421 return null ;
423- assert (scope != null , 'a Localizations ancestor was not found' );
422+ assert (() {
423+ if (scope == null ) {
424+ throw FlutterError (
425+ 'Requested the Locale of a context that does not include a Localizations ancestor.\n '
426+ 'To request the Locale, the context used to retrieve the Localizations widget must '
427+ 'be that of a widget that is a descendant of a Localizations widget.'
428+ );
429+ }
430+ if (! nullOk && scope.localizationsState.locale == null ) {
431+ throw FlutterError (
432+ 'Localizations.localeOf found a Localizations widget that had a unexpected null locale.\n '
433+ );
434+ }
435+ return true ;
436+ }());
424437 return scope! .localizationsState.locale;
425438 }
426439
440+ /// The locale of the Localizations widget for the widget tree that
441+ /// corresponds to [BuildContext] `context` .
442+ ///
443+ /// If no [Localizations] widget is in scope then this function will return
444+ /// null. Equivalent to calling [localeOf] with `nullOk` set to true.
445+ static Locale ? maybeLocaleOf (BuildContext context) {
446+ assert (context != null );
447+ final _LocalizationsScope ? scope = context.dependOnInheritedWidgetOfExactType <_LocalizationsScope >();
448+ return scope? .localizationsState.locale;
449+ }
450+
427451 // There doesn't appear to be a need to make this public. See the
428452 // Localizations.override factory constructor.
429453 static List <LocalizationsDelegate <dynamic >> _delegatesOf (BuildContext context) {
0 commit comments