app.dart 74.7 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:collection' show HashMap;
6

7
import 'package:flutter/foundation.dart';
8
import 'package:flutter/rendering.dart';
9
import 'package:flutter/services.dart';
10

11
import 'actions.dart';
12
import 'banner.dart';
13 14
import 'basic.dart';
import 'binding.dart';
15
import 'default_text_editing_shortcuts.dart';
16
import 'focus_scope.dart';
17
import 'focus_traversal.dart';
18
import 'framework.dart';
19
import 'localizations.dart';
20 21
import 'media_query.dart';
import 'navigator.dart';
22
import 'pages.dart';
23
import 'performance_overlay.dart';
24
import 'restoration.dart';
25
import 'router.dart';
26
import 'scrollable.dart';
27
import 'semantics_debugger.dart';
28
import 'shared_app_data.dart';
29
import 'shortcuts.dart';
30
import 'tap_region.dart';
31
import 'text.dart';
32
import 'title.dart';
33
import 'widget_inspector.dart';
34

35
export 'dart:ui' show Locale;
36

37 38 39
// Examples can assume:
// late Widget myWidget;

40 41 42 43 44 45 46 47 48
/// The signature of [WidgetsApp.localeListResolutionCallback].
///
/// A [LocaleListResolutionCallback] is responsible for computing the locale of the app's
/// [Localizations] object when the app starts and when user changes the list of
/// locales for the device.
///
/// The [locales] list is the device's preferred locales when the app started, or the
/// device's preferred locales the user selected after the app was started. This list
/// is in order of preference. If this list is null or empty, then Flutter has not yet
49
/// received the locale information from the platform. The [supportedLocales] parameter
50 51 52 53 54 55 56
/// is just the value of [WidgetsApp.supportedLocales].
///
/// See also:
///
///  * [LocaleResolutionCallback], which takes only one default locale (instead of a list)
///    and is attempted only after this callback fails or is null. [LocaleListResolutionCallback]
///    is recommended over [LocaleResolutionCallback].
57
typedef LocaleListResolutionCallback = Locale? Function(List<Locale>? locales, Iterable<Locale> supportedLocales);
58

59
/// {@template flutter.widgets.LocaleResolutionCallback}
60 61
/// The signature of [WidgetsApp.localeResolutionCallback].
///
62
/// It is recommended to provide a [LocaleListResolutionCallback] instead of a
63
/// [LocaleResolutionCallback] when possible, as [LocaleResolutionCallback] only
64
/// receives a subset of the information provided in [LocaleListResolutionCallback].
65 66
///
/// A [LocaleResolutionCallback] is responsible for computing the locale of the app's
67
/// [Localizations] object when the app starts and when user changes the default
68
/// locale for the device after [LocaleListResolutionCallback] fails or is not provided.
69
///
70
/// This callback is also used if the app is created with a specific locale using
71
/// the [WidgetsApp.new] `locale` parameter.
72
///
73 74 75
/// The [locale] is either the value of [WidgetsApp.locale], or the device's default
/// locale when the app started, or the device locale the user selected after the app
/// was started. The default locale is the first locale in the list of preferred
76
/// locales. If [locale] is null, then Flutter has not yet received the locale
77
/// information from the platform. The [supportedLocales] parameter is just the value of
78
/// [WidgetsApp.supportedLocales].
79 80 81 82 83
///
/// See also:
///
///  * [LocaleListResolutionCallback], which takes a list of preferred locales (instead of one locale).
///    Resolutions by [LocaleListResolutionCallback] take precedence over [LocaleResolutionCallback].
Dan Field's avatar
Dan Field committed
84
/// {@endtemplate}
85
typedef LocaleResolutionCallback = Locale? Function(Locale? locale, Iterable<Locale> supportedLocales);
86

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
/// The default locale resolution algorithm.
///
/// Custom resolution algorithms can be provided through
/// [WidgetsApp.localeListResolutionCallback] or
/// [WidgetsApp.localeResolutionCallback].
///
/// When no custom locale resolution algorithms are provided or if both fail
/// to resolve, Flutter will default to calling this algorithm.
///
/// This algorithm prioritizes speed at the cost of slightly less appropriate
/// resolutions for edge cases.
///
/// This algorithm will resolve to the earliest preferred locale that
/// matches the most fields, prioritizing in the order of perfect match,
/// languageCode+countryCode, languageCode+scriptCode, languageCode-only.
///
/// In the case where a locale is matched by languageCode-only and is not the
/// default (first) locale, the next preferred locale with a
/// perfect match can supersede the languageCode-only match if it exists.
///
/// When a preferredLocale matches more than one supported locale, it will
/// resolve to the first matching locale listed in the supportedLocales.
///
/// When all preferred locales have been exhausted without a match, the first
/// countryCode only match will be returned.
///
/// When no match at all is found, the first (default) locale in
/// [supportedLocales] will be returned.
///
/// To summarize, the main matching priority is:
///
///  1. [Locale.languageCode], [Locale.scriptCode], and [Locale.countryCode]
119 120 121 122 123
///  2. [Locale.languageCode] and [Locale.scriptCode] only
///  3. [Locale.languageCode] and [Locale.countryCode] only
///  4. [Locale.languageCode] only (with caveats, see above)
///  5. [Locale.countryCode] only when all [preferredLocales] fail to match
///  6. Returns the first element of [supportedLocales] as a fallback
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
///
/// This algorithm does not take language distance (how similar languages are to each other)
/// into account, and will not handle edge cases such as resolving `de` to `fr` rather than `zh`
/// when `de` is not supported and `zh` is listed before `fr` (German is closer to French
/// than Chinese).
Locale basicLocaleListResolution(List<Locale>? preferredLocales, Iterable<Locale> supportedLocales) {
  // preferredLocales can be null when called before the platform has had a chance to
  // initialize the locales. Platforms without locale passing support will provide an empty list.
  // We default to the first supported locale in these cases.
  if (preferredLocales == null || preferredLocales.isEmpty) {
    return supportedLocales.first;
  }
  // Hash the supported locales because apps can support many locales and would
  // be expensive to search through them many times.
  final Map<String, Locale> allSupportedLocales = HashMap<String, Locale>();
  final Map<String, Locale> languageAndCountryLocales = HashMap<String, Locale>();
  final Map<String, Locale> languageAndScriptLocales = HashMap<String, Locale>();
  final Map<String, Locale> languageLocales = HashMap<String, Locale>();
  final Map<String?, Locale> countryLocales = HashMap<String?, Locale>();
  for (final Locale locale in supportedLocales) {
    allSupportedLocales['${locale.languageCode}_${locale.scriptCode}_${locale.countryCode}'] ??= locale;
    languageAndScriptLocales['${locale.languageCode}_${locale.scriptCode}'] ??= locale;
    languageAndCountryLocales['${locale.languageCode}_${locale.countryCode}'] ??= locale;
    languageLocales[locale.languageCode] ??= locale;
    countryLocales[locale.countryCode] ??= locale;
  }

  // Since languageCode-only matches are possibly low quality, we don't return
  // it instantly when we find such a match. We check to see if the next
  // preferred locale in the list has a high accuracy match, and only return
  // the languageCode-only match when a higher accuracy match in the next
  // preferred locale cannot be found.
  Locale? matchesLanguageCode;
  Locale? matchesCountryCode;
  // Loop over user's preferred locales
  for (int localeIndex = 0; localeIndex < preferredLocales.length; localeIndex += 1) {
    final Locale userLocale = preferredLocales[localeIndex];
    // Look for perfect match.
    if (allSupportedLocales.containsKey('${userLocale.languageCode}_${userLocale.scriptCode}_${userLocale.countryCode}')) {
      return userLocale;
    }
    // Look for language+script match.
    if (userLocale.scriptCode != null) {
      final Locale? match = languageAndScriptLocales['${userLocale.languageCode}_${userLocale.scriptCode}'];
      if (match != null) {
        return match;
      }
    }
    // Look for language+country match.
    if (userLocale.countryCode != null) {
      final Locale? match = languageAndCountryLocales['${userLocale.languageCode}_${userLocale.countryCode}'];
      if (match != null) {
        return match;
      }
    }
    // If there was a languageCode-only match in the previous iteration's higher
    // ranked preferred locale, we return it if the current userLocale does not
    // have a better match.
    if (matchesLanguageCode != null) {
      return matchesLanguageCode;
    }
    // Look and store language-only match.
    Locale? match = languageLocales[userLocale.languageCode];
    if (match != null) {
      matchesLanguageCode = match;
      // Since first (default) locale is usually highly preferred, we will allow
      // a languageCode-only match to be instantly matched. If the next preferred
      // languageCode is the same, we defer hastily returning until the next iteration
      // since at worst it is the same and at best an improved match.
      if (localeIndex == 0 &&
          !(localeIndex + 1 < preferredLocales.length && preferredLocales[localeIndex + 1].languageCode == userLocale.languageCode)) {
        return matchesLanguageCode;
      }
    }
    // countryCode-only match. When all else except default supported locale fails,
    // attempt to match by country only, as a user is likely to be familiar with a
    // language from their listed country.
    if (matchesCountryCode == null && userLocale.countryCode != null) {
      match = countryLocales[userLocale.countryCode];
      if (match != null) {
        matchesCountryCode = match;
      }
    }
  }
  // When there is no languageCode-only match. Fallback to matching countryCode only. Country
  // fallback only applies on iOS. When there is no countryCode-only match, we return first
  // supported locale.
  final Locale resolvedLocale = matchesLanguageCode ?? matchesCountryCode ?? supportedLocales.first;
  return resolvedLocale;
}

215 216 217
/// The signature of [WidgetsApp.onGenerateTitle].
///
/// Used to generate a value for the app's [Title.title], which the device uses
218
/// to identify the app for the user. The `context` includes the [WidgetsApp]'s
219 220 221 222
/// [Localizations] widget so that this method can be used to produce a
/// localized title.
///
/// This function must not return null.
223
typedef GenerateAppTitle = String Function(BuildContext context);
224

225 226 227
/// The signature of [WidgetsApp.pageRouteBuilder].
///
/// Creates a [PageRoute] using the given [RouteSettings] and [WidgetBuilder].
228
typedef PageRouteFactory = PageRoute<T> Function<T>(RouteSettings settings, WidgetBuilder builder);
229

230 231 232 233 234
/// The signature of [WidgetsApp.onGenerateInitialRoutes].
///
/// Creates a series of one or more initial routes.
typedef InitialRouteListFactory = List<Route<dynamic>> Function(String initialRoute);

235
/// A convenience widget that wraps a number of widgets that are commonly
Ian Hickson's avatar
Ian Hickson committed
236 237
/// required for an application.
///
238 239 240
/// One of the primary roles that [WidgetsApp] provides is binding the system
/// back button to popping the [Navigator] or quitting the application.
///
241 242 243
/// It is used by both [MaterialApp] and [CupertinoApp] to implement base
/// functionality for an app.
///
244 245 246
/// Builds a [MediaQuery] using [MediaQuery.fromWindow]. To use an inherited
/// [MediaQuery] instead, set [useInheritedMediaQuery] to true.
///
247 248 249 250 251 252
/// Find references to many of the widgets that [WidgetsApp] wraps in the "See
/// also" section.
///
/// See also:
///
///  * [CheckedModeBanner], which displays a [Banner] saying "DEBUG" when
253
///    running in debug mode.
254 255 256 257
///  * [DefaultTextStyle], the text style to apply to descendant [Text] widgets
///    without an explicit style.
///  * [MediaQuery], which establishes a subtree in which media queries resolve
///    to a [MediaQueryData].
258 259
///  * [MediaQuery.fromWindow], which builds a [MediaQuery] with data derived
///    from [WidgetsBinding.window].
260 261 262 263 264 265 266
///  * [Localizations], which defines the [Locale] for its `child`.
///  * [Title], a widget that describes this app in the operating system.
///  * [Navigator], a widget that manages a set of child widgets with a stack
///    discipline.
///  * [Overlay], a widget that manages a [Stack] of entries that can be managed
///    independently.
///  * [SemanticsDebugger], a widget that visualizes the semantics for the child.
267
class WidgetsApp extends StatefulWidget {
268 269
  /// Creates a widget that wraps a number of widgets that are commonly
  /// required for an application.
270
  ///
271 272
  /// The boolean arguments, [color], and [navigatorObservers] must not be null.
  ///
273 274 275 276 277 278 279 280
  /// Most callers will want to use the [home] or [routes] parameters, or both.
  /// The [home] parameter is a convenience for the following [routes] map:
  ///
  /// ```dart
  /// <String, WidgetBuilder>{ '/': (BuildContext context) => myWidget }
  /// ```
  ///
  /// It is possible to specify both [home] and [routes], but only if [routes] does
281
  ///  _not_ contain an entry for `'/'`. Conversely, if [home] is omitted, [routes]
282 283
  /// _must_ contain an entry for `'/'`.
  ///
284
  /// If [home] or [routes] are not null, the routing implementation needs to know how
285
  /// appropriately build [PageRoute]s. This can be achieved by supplying the
286
  /// [pageRouteBuilder] parameter. The [pageRouteBuilder] is used by [MaterialApp]
287 288 289 290 291 292 293 294
  /// and [CupertinoApp] to create [MaterialPageRoute]s and [CupertinoPageRoute],
  /// respectively.
  ///
  /// The [builder] parameter is designed to provide the ability to wrap the visible
  /// content of the app in some other widget. It is recommended that you use [home]
  /// rather than [builder] if you intend to only display a single route in your app.
  ///
  /// [WidgetsApp] is also possible to provide a custom implementation of routing via the
295
  /// [onGenerateRoute] and [onUnknownRoute] parameters. These parameters correspond
296 297
  /// to [Navigator.onGenerateRoute] and [Navigator.onUnknownRoute]. If [home], [routes],
  /// and [builder] are null, or if they fail to create a requested route,
298
  /// [onGenerateRoute] will be invoked. If that fails, [onUnknownRoute] will be invoked.
299
  ///
300
  /// The [pageRouteBuilder] is called to create a [PageRoute] that wraps newly built routes.
301
  /// If the [builder] is non-null and the [onGenerateRoute] argument is null, then the
302 303 304 305
  /// [builder] will be provided only with the context and the child widget, whereas
  /// the [pageRouteBuilder] will be provided with [RouteSettings]; in that configuration,
  /// the [navigatorKey], [onUnknownRoute], [navigatorObservers], and
  /// [initialRoute] properties must have their default values, as they will have no effect.
306 307 308
  ///
  /// The `supportedLocales` argument must be a list of one or more elements.
  /// By default supportedLocales is `[const Locale('en', 'US')]`.
309 310 311 312 313 314
  ///
  /// {@tool dartpad}
  /// This sample shows a basic Flutter application using [WidgetsApp].
  ///
  /// ** See code in examples/api/lib/widgets/app/widgets_app.widgets_app.0.dart **
  /// {@end-tool}
315
  WidgetsApp({ // can't be const because the asserts use methods on Iterable :-(
316
    super.key,
317
    this.navigatorKey,
318
    this.onGenerateRoute,
319
    this.onGenerateInitialRoutes,
320
    this.onUnknownRoute,
321
    List<NavigatorObserver> this.navigatorObservers = const <NavigatorObserver>[],
322
    this.initialRoute,
323 324
    this.pageRouteBuilder,
    this.home,
325
    Map<String, WidgetBuilder> this.routes = const <String, WidgetBuilder>{},
326
    this.builder,
327
    this.title = '',
328
    this.onGenerateTitle,
329
    this.textStyle,
330
    required this.color,
331 332
    this.locale,
    this.localizationsDelegates,
333
    this.localeListResolutionCallback,
334
    this.localeResolutionCallback,
335
    this.supportedLocales = const <Locale>[Locale('en', 'US')],
336 337 338 339 340 341
    this.showPerformanceOverlay = false,
    this.checkerboardRasterCacheImages = false,
    this.checkerboardOffscreenLayers = false,
    this.showSemanticsDebugger = false,
    this.debugShowWidgetInspector = false,
    this.debugShowCheckedModeBanner = true,
342
    this.inspectorSelectButtonBuilder,
343 344
    this.shortcuts,
    this.actions,
345
    this.restorationScopeId,
346
    this.useInheritedMediaQuery = false,
347
  }) : assert(navigatorObservers != null),
348
       assert(routes != null),
349 350 351
       assert(
         home == null ||
         onGenerateInitialRoutes == null,
352
         'If onGenerateInitialRoutes is specified, the home argument will be '
353
         'redundant.',
354
       ),
355 356 357 358
       assert(
         home == null ||
         !routes.containsKey(Navigator.defaultRouteName),
         'If the home property is specified, the routes table '
359
         'cannot include an entry for "/", since it would be redundant.',
360 361 362 363 364 365 366 367 368 369 370 371 372
       ),
       assert(
         builder != null ||
         home != null ||
         routes.containsKey(Navigator.defaultRouteName) ||
         onGenerateRoute != null ||
         onUnknownRoute != null,
         'Either the home property must be specified, '
         'or the routes table must include an entry for "/", '
         'or there must be on onGenerateRoute callback specified, '
         'or there must be an onUnknownRoute callback specified, '
         'or the builder property must be specified, '
         'because otherwise there is nothing to fall back on if the '
373
         'app is started with an intent that specifies an unknown route.',
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
       ),
       assert(
         (home != null ||
          routes.isNotEmpty ||
          onGenerateRoute != null ||
          onUnknownRoute != null)
         ||
         (builder != null &&
          navigatorKey == null &&
          initialRoute == null &&
          navigatorObservers.isEmpty),
         'If no route is provided using '
         'home, routes, onGenerateRoute, or onUnknownRoute, '
         'a non-null callback for the builder property must be provided, '
         'and the other navigator-related properties, '
         'navigatorKey, initialRoute, and navigatorObservers, '
         'must have their initial values '
391
         '(null, null, and the empty list, respectively).',
392
       ),
393 394 395 396 397 398
       assert(
         builder != null ||
         onGenerateRoute != null ||
         pageRouteBuilder != null,
         'If neither builder nor onGenerateRoute are provided, the '
         'pageRouteBuilder must be specified so that the default handler '
399
         'will know what kind of PageRoute transition to build.',
400
       ),
401
       assert(title != null),
402
       assert(color != null),
403
       assert(supportedLocales != null && supportedLocales.isNotEmpty),
404 405
       assert(showPerformanceOverlay != null),
       assert(checkerboardRasterCacheImages != null),
406
       assert(checkerboardOffscreenLayers != null),
407
       assert(showSemanticsDebugger != null),
408
       assert(debugShowCheckedModeBanner != null),
409
       assert(debugShowWidgetInspector != null),
410 411 412
       routeInformationProvider = null,
       routeInformationParser = null,
       routerDelegate = null,
413 414
       backButtonDispatcher = null,
       routerConfig = null;
415 416

  /// Creates a [WidgetsApp] that uses the [Router] instead of a [Navigator].
417 418 419 420 421 422
  ///
  /// {@template flutter.widgets.WidgetsApp.router}
  /// If the [routerConfig] is provided, the other router related delegates,
  /// [routeInformationParser], [routeInformationProvider], [routerDelegate],
  /// and [backButtonDispatcher], must all be null.
  /// {@endtemplate}
423
  WidgetsApp.router({
424
    super.key,
425
    this.routeInformationProvider,
426 427 428 429
    this.routeInformationParser,
    this.routerDelegate,
    this.routerConfig,
    this.backButtonDispatcher,
430 431 432 433
    this.builder,
    this.title = '',
    this.onGenerateTitle,
    this.textStyle,
434
    required this.color,
435 436 437 438 439 440 441 442 443 444 445 446 447 448
    this.locale,
    this.localizationsDelegates,
    this.localeListResolutionCallback,
    this.localeResolutionCallback,
    this.supportedLocales = const <Locale>[Locale('en', 'US')],
    this.showPerformanceOverlay = false,
    this.checkerboardRasterCacheImages = false,
    this.checkerboardOffscreenLayers = false,
    this.showSemanticsDebugger = false,
    this.debugShowWidgetInspector = false,
    this.debugShowCheckedModeBanner = true,
    this.inspectorSelectButtonBuilder,
    this.shortcuts,
    this.actions,
449
    this.restorationScopeId,
450
    this.useInheritedMediaQuery = false,
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
  }) : assert((){
         if (routerConfig != null) {
           assert(
             (routeInformationProvider ?? routeInformationParser ?? routerDelegate ?? backButtonDispatcher) == null,
             'If the routerConfig is provided, all the other router delegates must not be provided',
           );
           return true;
         }
         assert(routerDelegate != null, 'Either one of routerDelegate or routerConfig must be provided');
         assert(
           routeInformationProvider == null || routeInformationParser != null,
           'If routeInformationProvider is provided, routeInformationParser must also be provided',
         );
         return true;
       }()),
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
       assert(title != null),
       assert(color != null),
       assert(supportedLocales != null && supportedLocales.isNotEmpty),
       assert(showPerformanceOverlay != null),
       assert(checkerboardRasterCacheImages != null),
       assert(checkerboardOffscreenLayers != null),
       assert(showSemanticsDebugger != null),
       assert(debugShowCheckedModeBanner != null),
       assert(debugShowWidgetInspector != null),
       navigatorObservers = null,
       navigatorKey = null,
       onGenerateRoute = null,
       pageRouteBuilder = null,
       home = null,
       onGenerateInitialRoutes = null,
       onUnknownRoute = null,
       routes = null,
483
       initialRoute = null;
484

485
  /// {@template flutter.widgets.widgetsApp.navigatorKey}
486 487 488 489 490 491 492 493 494 495 496
  /// A key to use when building the [Navigator].
  ///
  /// If a [navigatorKey] is specified, the [Navigator] can be directly
  /// manipulated without first obtaining it from a [BuildContext] via
  /// [Navigator.of]: from the [navigatorKey], use the [GlobalKey.currentState]
  /// getter.
  ///
  /// If this is changed, a new [Navigator] will be created, losing all the
  /// application state in the process; in that case, the [navigatorObservers]
  /// must also be changed, since the previous observers will be attached to the
  /// previous navigator.
497
  ///
498 499
  /// The [Navigator] is only built if [onGenerateRoute] is not null; if it is
  /// null, [navigatorKey] must also be null.
500
  /// {@endtemplate}
501
  final GlobalKey<NavigatorState>? navigatorKey;
502

xster's avatar
xster committed
503
  /// {@template flutter.widgets.widgetsApp.onGenerateRoute}
504
  /// The route generator callback used when the app is navigated to a
Ian Hickson's avatar
Ian Hickson committed
505
  /// named route.
506 507 508 509 510 511 512 513
  ///
  /// If this returns null when building the routes to handle the specified
  /// [initialRoute], then all the routes are discarded and
  /// [Navigator.defaultRouteName] is used instead (`/`). See [initialRoute].
  ///
  /// During normal app operation, the [onGenerateRoute] callback will only be
  /// applied to route names pushed by the application, and so should never
  /// return null.
514 515 516 517 518 519
  ///
  /// This is used if [routes] does not contain the requested route.
  ///
  /// The [Navigator] is only built if routes are provided (either via [home],
  /// [routes], [onGenerateRoute], or [onUnknownRoute]); if they are not,
  /// [builder] must not be null.
xster's avatar
xster committed
520
  /// {@endtemplate}
521
  ///
522 523 524
  /// If this property is not set, either the [routes] or [home] properties must
  /// be set, and the [pageRouteBuilder] must also be set so that the
  /// default handler will know what routes and [PageRoute]s to build.
525
  final RouteFactory? onGenerateRoute;
526

527 528 529 530 531 532 533 534
  /// {@template flutter.widgets.widgetsApp.onGenerateInitialRoutes}
  /// The routes generator callback used for generating initial routes if
  /// [initialRoute] is provided.
  ///
  /// If this property is not set, the underlying
  /// [Navigator.onGenerateInitialRoutes] will default to
  /// [Navigator.defaultGenerateInitialRoutes].
  /// {@endtemplate}
535
  final InitialRouteListFactory? onGenerateInitialRoutes;
536

537 538 539
  /// The [PageRoute] generator callback used when the app is navigated to a
  /// named route.
  ///
540 541 542 543
  /// A [PageRoute] represents the page in a [Navigator], so that it can
  /// correctly animate between pages, and to represent the "return value" of
  /// a route (e.g. which button a user selected in a modal dialog).
  ///
544 545
  /// This callback can be used, for example, to specify that a [MaterialPageRoute]
  /// or a [CupertinoPageRoute] should be used for building page transitions.
546 547 548 549 550 551 552 553 554 555 556
  ///
  /// The [PageRouteFactory] type is generic, meaning the provided function must
  /// itself be generic. For example (with special emphasis on the `<T>` at the
  /// start of the closure):
  ///
  /// ```dart
  /// pageRouteBuilder: <T>(RouteSettings settings, WidgetBuilder builder) => PageRouteBuilder<T>(
  ///   settings: settings,
  ///   pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) => builder(context),
  /// ),
  /// ```
557
  final PageRouteFactory? pageRouteBuilder;
558

559 560 561 562 563 564 565 566 567 568 569
  /// {@template flutter.widgets.widgetsApp.routeInformationParser}
  /// A delegate to parse the route information from the
  /// [routeInformationProvider] into a generic data type to be processed by
  /// the [routerDelegate] at a later stage.
  ///
  /// This object will be used by the underlying [Router].
  ///
  /// The generic type `T` must match the generic type of the [routerDelegate].
  ///
  /// See also:
  ///
570
  ///  * [Router.routeInformationParser], which receives this object when this
571 572
  ///    widget builds the [Router].
  /// {@endtemplate}
573
  final RouteInformationParser<Object>? routeInformationParser;
574 575 576 577 578 579 580 581 582 583 584 585

  /// {@template flutter.widgets.widgetsApp.routerDelegate}
  /// A delegate that configures a widget, typically a [Navigator], with
  /// parsed result from the [routeInformationParser].
  ///
  /// This object will be used by the underlying [Router].
  ///
  /// The generic type `T` must match the generic type of the
  /// [routeInformationParser].
  ///
  /// See also:
  ///
586
  ///  * [Router.routerDelegate], which receives this object when this widget
587 588
  ///    builds the [Router].
  /// {@endtemplate}
589
  final RouterDelegate<Object>? routerDelegate;
590 591 592 593 594 595 596 597 598 599 600

  /// {@template flutter.widgets.widgetsApp.backButtonDispatcher}
  /// A delegate that decide whether to handle the Android back button intent.
  ///
  /// This object will be used by the underlying [Router].
  ///
  /// If this is not provided, the widgets app will create a
  /// [RootBackButtonDispatcher] by default.
  ///
  /// See also:
  ///
601
  ///  * [Router.backButtonDispatcher], which receives this object when this
602 603
  ///    widget builds the [Router].
  /// {@endtemplate}
604
  final BackButtonDispatcher? backButtonDispatcher;
605 606 607 608 609 610 611 612 613

  /// {@template flutter.widgets.widgetsApp.routeInformationProvider}
  /// A object that provides route information through the
  /// [RouteInformationProvider.value] and notifies its listener when its value
  /// changes.
  ///
  /// This object will be used by the underlying [Router].
  ///
  /// If this is not provided, the widgets app will create a
614 615
  /// [PlatformRouteInformationProvider] with initial route name equal to the
  /// [dart:ui.PlatformDispatcher.defaultRouteName] by default.
616 617 618
  ///
  /// See also:
  ///
619
  ///  * [Router.routeInformationProvider], which receives this object when this
620 621
  ///    widget builds the [Router].
  /// {@endtemplate}
622
  final RouteInformationProvider? routeInformationProvider;
623

624 625 626 627 628 629 630 631 632 633 634 635 636 637
  /// {@template flutter.widgets.widgetsApp.routerConfig}
  /// An object to configure the underlying [Router].
  ///
  /// If the [routerConfig] is provided, the other router related delegates,
  /// [routeInformationParser], [routeInformationProvider], [routerDelegate],
  /// and [backButtonDispatcher], must all be null.
  ///
  /// See also:
  ///
  ///  * [Router.withConfig], which receives this object when this
  ///    widget builds the [Router].
  /// {@endtemplate}
  final RouterConfig<Object>? routerConfig;

638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
  /// {@template flutter.widgets.widgetsApp.home}
  /// The widget for the default route of the app ([Navigator.defaultRouteName],
  /// which is `/`).
  ///
  /// This is the route that is displayed first when the application is started
  /// normally, unless [initialRoute] is specified. It's also the route that's
  /// displayed if the [initialRoute] can't be displayed.
  ///
  /// To be able to directly call [Theme.of], [MediaQuery.of], etc, in the code
  /// that sets the [home] argument in the constructor, you can use a [Builder]
  /// widget to get a [BuildContext].
  ///
  /// If [home] is specified, then [routes] must not include an entry for `/`,
  /// as [home] takes its place.
  ///
  /// The [Navigator] is only built if routes are provided (either via [home],
  /// [routes], [onGenerateRoute], or [onUnknownRoute]); if they are not,
  /// [builder] must not be null.
  ///
  /// The difference between using [home] and using [builder] is that the [home]
  /// subtree is inserted into the application below a [Navigator] (and thus
  /// below an [Overlay], which [Navigator] uses). With [home], therefore,
  /// dialog boxes will work automatically, the [routes] table will be used, and
  /// APIs such as [Navigator.push] and [Navigator.pop] will work as expected.
  /// In contrast, the widget returned from [builder] is inserted _above_ the
  /// app's [Navigator] (if any).
664
  /// {@endtemplate}
665 666 667 668
  ///
  /// If this property is set, the [pageRouteBuilder] property must also be set
  /// so that the default route handler will know what kind of [PageRoute]s to
  /// build.
669
  final Widget? home;
670 671 672 673 674

  /// The application's top-level routing table.
  ///
  /// When a named route is pushed with [Navigator.pushNamed], the route name is
  /// looked up in this map. If the name is present, the associated
Janice Collins's avatar
Janice Collins committed
675
  /// [widgets.WidgetBuilder] is used to construct a [PageRoute] specified by
676 677
  /// [pageRouteBuilder] to perform an appropriate transition, including [Hero]
  /// animations, to the new route.
678
  ///
679 680 681 682 683 684 685 686 687 688 689 690 691 692
  /// {@template flutter.widgets.widgetsApp.routes}
  /// If the app only has one page, then you can specify it using [home] instead.
  ///
  /// If [home] is specified, then it implies an entry in this table for the
  /// [Navigator.defaultRouteName] route (`/`), and it is an error to
  /// redundantly provide such a route in the [routes] table.
  ///
  /// If a route is requested that is not specified in this table (or by
  /// [home]), then the [onGenerateRoute] callback is called to build the page
  /// instead.
  ///
  /// The [Navigator] is only built if routes are provided (either via [home],
  /// [routes], [onGenerateRoute], or [onUnknownRoute]); if they are not,
  /// [builder] must not be null.
693
  /// {@endtemplate}
694 695 696 697
  ///
  /// If the routes map is not empty, the [pageRouteBuilder] property must be set
  /// so that the default route handler will know what kind of [PageRoute]s to
  /// build.
698
  final Map<String, WidgetBuilder>? routes;
699

xster's avatar
xster committed
700
  /// {@template flutter.widgets.widgetsApp.onUnknownRoute}
701 702 703
  /// Called when [onGenerateRoute] fails to generate a route, except for the
  /// [initialRoute].
  ///
704 705 706 707 708 709
  /// This callback is typically used for error handling. For example, this
  /// callback might always generate a "not found" page that describes the route
  /// that wasn't found.
  ///
  /// Unknown routes can arise either from errors in the app or from external
  /// requests to push routes, such as from Android intents.
710
  ///
711 712 713 714
  /// The [Navigator] is only built if routes are provided (either via [home],
  /// [routes], [onGenerateRoute], or [onUnknownRoute]); if they are not,
  /// [builder] must not be null.
  /// {@endtemplate}
715
  final RouteFactory? onUnknownRoute;
716

xster's avatar
xster committed
717 718
  /// {@template flutter.widgets.widgetsApp.initialRoute}
  /// The name of the first route to show, if a [Navigator] is built.
719
  ///
720 721
  /// Defaults to [dart:ui.PlatformDispatcher.defaultRouteName], which may be
  /// overridden by the code that launched the application.
722
  ///
723 724 725 726 727 728 729
  /// If the route name starts with a slash, then it is treated as a "deep link",
  /// and before this route is pushed, the routes leading to this one are pushed
  /// also. For example, if the route was `/a/b/c`, then the app would start
  /// with the four routes `/`, `/a`, `/a/b`, and `/a/b/c` loaded, in that order.
  /// Even if the route was just `/a`, the app would start with `/` and `/a`
  /// loaded. You can use the [onGenerateInitialRoutes] property to override
  /// this behavior.
730
  ///
731 732 733 734 735 736
  /// Intermediate routes aren't required to exist. In the example above, `/a`
  /// and `/a/b` could be skipped if they have no matching route. But `/a/b/c` is
  /// required to have a route, else [initialRoute] is ignored and
  /// [Navigator.defaultRouteName] is used instead (`/`). This can happen if the
  /// app is started with an intent that specifies a non-existent route.
  ///
737 738 739
  /// The [Navigator] is only built if routes are provided (either via [home],
  /// [routes], [onGenerateRoute], or [onUnknownRoute]); if they are not,
  /// [initialRoute] must be null and [builder] must not be null.
740
  ///
741 742 743 744 745
  /// See also:
  ///
  ///  * [Navigator.initialRoute], which is used to implement this property.
  ///  * [Navigator.push], for pushing additional routes.
  ///  * [Navigator.pop], for removing a route from the stack.
746
  ///
747
  /// {@endtemplate}
748
  final String? initialRoute;
749

xster's avatar
xster committed
750
  /// {@template flutter.widgets.widgetsApp.navigatorObservers}
751 752 753 754
  /// The list of observers for the [Navigator] created for this app.
  ///
  /// This list must be replaced by a list of newly-created observers if the
  /// [navigatorKey] is changed.
755
  ///
756 757 758 759
  /// The [Navigator] is only built if routes are provided (either via [home],
  /// [routes], [onGenerateRoute], or [onUnknownRoute]); if they are not,
  /// [navigatorObservers] must be the empty list and [builder] must not be null.
  /// {@endtemplate}
760
  final List<NavigatorObserver>? navigatorObservers;
761

xster's avatar
xster committed
762
  /// {@template flutter.widgets.widgetsApp.builder}
763 764 765 766
  /// A builder for inserting widgets above the [Navigator] or - when the
  /// [WidgetsApp.router] constructor is used - above the [Router] but below the
  /// other widgets created by the [WidgetsApp] widget, or for replacing the
  /// [Navigator]/[Router] entirely.
767 768 769 770
  ///
  /// For example, from the [BuildContext] passed to this method, the
  /// [Directionality], [Localizations], [DefaultTextStyle], [MediaQuery], etc,
  /// are all available. They can also be overridden in a way that impacts all
771
  /// the routes in the [Navigator] or [Router].
772 773 774 775 776 777
  ///
  /// This is rarely useful, but can be used in applications that wish to
  /// override those defaults, e.g. to force the application into right-to-left
  /// mode despite being in English, or to override the [MediaQuery] metrics
  /// (e.g. to leave a gap for advertisements shown by a plugin from OEM code).
  ///
xster's avatar
xster committed
778 779 780
  /// For specifically overriding the [title] with a value based on the
  /// [Localizations], consider [onGenerateTitle] instead.
  ///
781
  /// The [builder] callback is passed two arguments, the [BuildContext] (as
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
  /// `context`) and a [Navigator] or [Router] widget (as `child`).
  ///
  /// If no routes are provided to the regular [WidgetsApp] constructor using
  /// [home], [routes], [onGenerateRoute], or [onUnknownRoute], the `child` will
  /// be null, and it is the responsibility of the [builder] to provide the
  /// application's routing machinery.
  ///
  /// If routes _are_ provided to the regular [WidgetsApp] constructor using one
  /// or more of those properties or if the [WidgetsApp.router] constructor is
  /// used, then `child` is not null, and the returned value should include the
  /// `child` in the widget subtree; if it does not, then the application will
  /// have no [Navigator] or [Router] and the routing related properties (i.e.
  /// [navigatorKey], [home], [routes], [onGenerateRoute], [onUnknownRoute],
  /// [initialRoute], [navigatorObservers], [routeInformationProvider],
  /// [backButtonDispatcher], [routerDelegate], and [routeInformationParser])
  /// are ignored.
798 799
  ///
  /// If [builder] is null, it is as if a builder was specified that returned
800 801 802 803 804
  /// the `child` directly. If it is null, routes must be provided using one of
  /// the other properties listed above.
  ///
  /// Unless a [Navigator] is provided, either implicitly from [builder] being
  /// null, or by a [builder] including its `child` argument, or by a [builder]
805 806 807
  /// explicitly providing a [Navigator] of its own, or by the [routerDelegate]
  /// building one, widgets and APIs such as [Hero], [Navigator.push] and
  /// [Navigator.pop], will not function.
808
  /// {@endtemplate}
809
  final TransitionBuilder? builder;
810

xster's avatar
xster committed
811
  /// {@template flutter.widgets.widgetsApp.title}
812 813 814
  /// A one-line description used by the device to identify the app for the user.
  ///
  /// On Android the titles appear above the task manager's app snapshots which are
815 816 817
  /// displayed when the user presses the "recent apps" button. On iOS this
  /// value cannot be used. `CFBundleDisplayName` from the app's `Info.plist` is
  /// referred to instead whenever present, `CFBundleName` otherwise.
818
  /// On the web it is used as the page title, which shows up in the browser's list of open tabs.
819 820
  ///
  /// To provide a localized title instead, use [onGenerateTitle].
xster's avatar
xster committed
821
  /// {@endtemplate}
822 823
  final String title;

xster's avatar
xster committed
824
  /// {@template flutter.widgets.widgetsApp.onGenerateTitle}
825 826 827 828 829 830 831 832 833 834 835
  /// If non-null this callback function is called to produce the app's
  /// title string, otherwise [title] is used.
  ///
  /// The [onGenerateTitle] `context` parameter includes the [WidgetsApp]'s
  /// [Localizations] widget so that this callback can be used to produce a
  /// localized title.
  ///
  /// This callback function must not return null.
  ///
  /// The [onGenerateTitle] callback is called each time the [WidgetsApp]
  /// rebuilds.
xster's avatar
xster committed
836
  /// {@endtemplate}
837
  final GenerateAppTitle? onGenerateTitle;
838 839

  /// The default text style for [Text] in the application.
840
  final TextStyle? textStyle;
841

xster's avatar
xster committed
842
  /// {@template flutter.widgets.widgetsApp.color}
843 844 845 846 847
  /// The primary color to use for the application in the operating system
  /// interface.
  ///
  /// For example, on Android this is the color used for the application in the
  /// application switcher.
xster's avatar
xster committed
848
  /// {@endtemplate}
849 850
  final Color color;

xster's avatar
xster committed
851
  /// {@template flutter.widgets.widgetsApp.locale}
852 853 854 855
  /// The initial locale for this app's [Localizations] widget is based
  /// on this value.
  ///
  /// If the 'locale' is null then the system's locale value is used.
856
  ///
857 858
  /// The value of [Localizations.locale] will equal this locale if
  /// it matches one of the [supportedLocales]. Otherwise it will be
Dan Field's avatar
Dan Field committed
859
  /// the first element of [supportedLocales].
xster's avatar
xster committed
860
  /// {@endtemplate}
861 862 863 864 865 866 867
  ///
  /// See also:
  ///
  ///  * [localeResolutionCallback], which can override the default
  ///    [supportedLocales] matching algorithm.
  ///  * [localizationsDelegates], which collectively define all of the localized
  ///    resources used by this app.
868
  final Locale? locale;
869

xster's avatar
xster committed
870
  /// {@template flutter.widgets.widgetsApp.localizationsDelegates}
871 872 873 874
  /// The delegates for this app's [Localizations] widget.
  ///
  /// The delegates collectively define all of the localized resources
  /// for this application's [Localizations] widget.
xster's avatar
xster committed
875
  /// {@endtemplate}
876
  final Iterable<LocalizationsDelegate<dynamic>>? localizationsDelegates;
877

878
  /// {@template flutter.widgets.widgetsApp.localeListResolutionCallback}
879 880 881 882
  /// This callback is responsible for choosing the app's locale
  /// when the app is started, and when the user changes the
  /// device's locale.
  ///
Dan Field's avatar
Dan Field committed
883 884 885 886 887
  /// When a [localeListResolutionCallback] is provided, Flutter will first
  /// attempt to resolve the locale with the provided
  /// [localeListResolutionCallback]. If the callback or result is null, it will
  /// fallback to trying the [localeResolutionCallback]. If both
  /// [localeResolutionCallback] and [localeListResolutionCallback] are left
nt4f04uNd's avatar
nt4f04uNd committed
888
  /// null or fail to resolve (return null), basic fallback algorithm will
Dan Field's avatar
Dan Field committed
889
  /// be used.
890
  ///
891
  /// The priority of each available fallback is:
892
  ///
nt4f04uNd's avatar
nt4f04uNd committed
893 894 895
  ///  1. [localeListResolutionCallback] is attempted.
  ///  2. [localeResolutionCallback] is attempted.
  ///  3. Flutter's basic resolution algorithm, as described in
Dan Field's avatar
Dan Field committed
896
  ///     [supportedLocales], is attempted last.
897 898
  ///
  /// Properly localized projects should provide a more advanced algorithm than
Dan Field's avatar
Dan Field committed
899 900 901
  /// the basic method from [supportedLocales], as it does not implement a
  /// complete algorithm (such as the one defined in
  /// [Unicode TR35](https://unicode.org/reports/tr35/#LanguageMatching))
902
  /// and is optimized for speed at the detriment of some uncommon edge-cases.
xster's avatar
xster committed
903
  /// {@endtemplate}
904
  ///
905 906 907
  /// This callback considers the entire list of preferred locales.
  ///
  /// This algorithm should be able to handle a null or empty list of preferred locales,
908
  /// which indicates Flutter has not yet received locale information from the platform.
909
  ///
910 911
  /// See also:
  ///
912
  ///  * [MaterialApp.localeListResolutionCallback], which sets the callback of the
913
  ///    [WidgetsApp] it creates.
914
  ///  * [basicLocaleListResolution], the default locale resolution algorithm.
915
  final LocaleListResolutionCallback? localeListResolutionCallback;
916 917 918 919 920 921 922 923

  /// {@macro flutter.widgets.widgetsApp.localeListResolutionCallback}
  ///
  /// This callback considers only the default locale, which is the first locale
  /// in the preferred locales list. It is preferred to set [localeListResolutionCallback]
  /// over [localeResolutionCallback] as it provides the full preferred locales list.
  ///
  /// This algorithm should be able to handle a null locale, which indicates
924
  /// Flutter has not yet received locale information from the platform.
925 926 927
  ///
  /// See also:
  ///
928
  ///  * [MaterialApp.localeResolutionCallback], which sets the callback of the
929
  ///    [WidgetsApp] it creates.
930
  ///  * [basicLocaleListResolution], the default locale resolution algorithm.
931
  final LocaleResolutionCallback? localeResolutionCallback;
932

xster's avatar
xster committed
933
  /// {@template flutter.widgets.widgetsApp.supportedLocales}
934 935 936 937 938 939 940 941
  /// The list of locales that this app has been localized for.
  ///
  /// By default only the American English locale is supported. Apps should
  /// configure this list to match the locales they support.
  ///
  /// This list must not null. Its default value is just
  /// `[const Locale('en', 'US')]`.
  ///
942
  /// The order of the list matters. The default locale resolution algorithm,
943
  /// [basicLocaleListResolution], attempts to match by the following priority:
944 945
  ///
  ///  1. [Locale.languageCode], [Locale.scriptCode], and [Locale.countryCode]
946 947 948 949 950
  ///  2. [Locale.languageCode] and [Locale.scriptCode] only
  ///  3. [Locale.languageCode] and [Locale.countryCode] only
  ///  4. [Locale.languageCode] only
  ///  5. [Locale.countryCode] only when all preferred locales fail to match
  ///  6. Returns the first element of [supportedLocales] as a fallback
Dan Field's avatar
Dan Field committed
951 952 953 954 955 956
  ///
  /// When more than one supported locale matches one of these criteria, only
  /// the first matching locale is returned.
  ///
  /// The default locale resolution algorithm can be overridden by providing a
  /// value for [localeListResolutionCallback]. The provided
957
  /// [basicLocaleListResolution] is optimized for speed and does not implement
Dan Field's avatar
Dan Field committed
958 959 960
  /// a full algorithm (such as the one defined in
  /// [Unicode TR35](https://unicode.org/reports/tr35/#LanguageMatching)) that
  /// takes distances between languages into account.
961 962 963 964 965 966
  ///
  /// When supporting languages with more than one script, it is recommended
  /// to specify the [Locale.scriptCode] explicitly. Locales may also be defined without
  /// [Locale.countryCode] to specify a generic fallback for a particular script.
  ///
  /// A fully supported language with multiple scripts should define a generic language-only
967 968
  /// locale (e.g. 'zh'), language+script only locales (e.g. 'zh_Hans' and 'zh_Hant'),
  /// and any language+script+country locales (e.g. 'zh_Hans_CN'). Fully defining all of
969 970 971 972 973 974
  /// these locales as supported is not strictly required but allows for proper locale resolution in
  /// the most number of cases. These locales can be specified with the [Locale.fromSubtags]
  /// constructor:
  ///
  /// ```dart
  /// // Full Chinese support for CN, TW, and HK
975
  /// supportedLocales: <Locale>[
976 977 978 979 980 981 982 983 984 985 986 987 988
  ///   const Locale.fromSubtags(languageCode: 'zh'), // generic Chinese 'zh'
  ///   const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans'), // generic simplified Chinese 'zh_Hans'
  ///   const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant'), // generic traditional Chinese 'zh_Hant'
  ///   const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'), // 'zh_Hans_CN'
  ///   const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'TW'), // 'zh_Hant_TW'
  ///   const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'HK'), // 'zh_Hant_HK'
  /// ],
  /// ```
  ///
  /// Omitting some these fallbacks may result in improperly resolved
  /// edge-cases, for example, a simplified Chinese user in Taiwan ('zh_Hans_TW')
  /// may resolve to traditional Chinese if 'zh_Hans' and 'zh_Hans_CN' are
  /// omitted.
xster's avatar
xster committed
989
  /// {@endtemplate}
990 991 992 993 994 995 996
  ///
  /// See also:
  ///
  ///  * [MaterialApp.supportedLocales], which sets the `supportedLocales`
  ///    of the [WidgetsApp] it creates.
  ///  * [localeResolutionCallback], an app callback that resolves the app's locale
  ///    when the device's locale changes.
997
  ///  * [localizationsDelegates], which collectively define all of the localized
998
  ///    resources used by this app.
999
  ///  * [basicLocaleListResolution], the default locale resolution algorithm.
1000 1001
  final Iterable<Locale> supportedLocales;

1002
  /// Turns on a performance overlay.
xster's avatar
xster committed
1003 1004 1005
  ///
  /// See also:
  ///
1006
  ///  * <https://flutter.dev/debugging/#performance-overlay>
1007 1008
  final bool showPerformanceOverlay;

1009
  /// Checkerboards raster cache images.
1010 1011
  ///
  /// See [PerformanceOverlay.checkerboardRasterCacheImages].
1012 1013
  final bool checkerboardRasterCacheImages;

1014 1015 1016 1017 1018
  /// Checkerboards layers rendered to offscreen bitmaps.
  ///
  /// See [PerformanceOverlay.checkerboardOffscreenLayers].
  final bool checkerboardOffscreenLayers;

1019 1020 1021 1022
  /// Turns on an overlay that shows the accessibility information
  /// reported by the framework.
  final bool showSemanticsDebugger;

1023 1024
  /// Turns on an overlay that enables inspecting the widget tree.
  ///
1025
  /// The inspector is only available in debug mode as it depends on
1026
  /// [RenderObject.debugDescribeChildren] which should not be called outside of
1027
  /// debug mode.
1028 1029 1030 1031 1032
  final bool debugShowWidgetInspector;

  /// Builds the widget the [WidgetInspector] uses to switch between view and
  /// inspect modes.
  ///
1033 1034
  /// This lets [MaterialApp] to use a Material Design button to toggle the
  /// inspector select mode without requiring [WidgetInspector] to depend on the
1035
  /// material package.
1036
  final InspectorSelectButtonBuilder? inspectorSelectButtonBuilder;
1037

xster's avatar
xster committed
1038
  /// {@template flutter.widgets.widgetsApp.debugShowCheckedModeBanner}
1039 1040 1041
  /// Turns on a little "DEBUG" banner in debug mode to indicate
  /// that the app is in debug mode. This is on by default (in
  /// debug mode), to turn it off, set the constructor argument to
1042 1043 1044 1045 1046
  /// false. In release mode this has no effect.
  ///
  /// To get this banner in your application if you're not using
  /// WidgetsApp, include a [CheckedModeBanner] widget in your app.
  ///
xster's avatar
xster committed
1047
  /// This banner is intended to deter people from complaining that your
1048
  /// app is slow when it's in debug mode. In debug mode, Flutter
1049
  /// enables a large number of expensive diagnostics to aid in
1050
  /// development, and so performance in debug mode is not
1051
  /// representative of what will happen in release mode.
xster's avatar
xster committed
1052
  /// {@endtemplate}
1053 1054
  final bool debugShowCheckedModeBanner;

1055 1056 1057 1058
  /// {@template flutter.widgets.widgetsApp.shortcuts}
  /// The default map of keyboard shortcuts to intents for the application.
  ///
  /// By default, this is set to [WidgetsApp.defaultShortcuts].
1059 1060 1061
  ///
  /// Passing this will not replace [DefaultTextEditingShortcuts]. These can be
  /// overridden by using a [Shortcuts] widget lower in the widget tree.
1062 1063
  /// {@endtemplate}
  ///
1064
  /// {@tool snippet}
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
  /// This example shows how to add a single shortcut for
  /// [LogicalKeyboardKey.select] to the default shortcuts without needing to
  /// add your own [Shortcuts] widget.
  ///
  /// Alternatively, you could insert a [Shortcuts] widget with just the mapping
  /// you want to add between the [WidgetsApp] and its child and get the same
  /// effect.
  ///
  /// ```dart
  /// Widget build(BuildContext context) {
  ///   return WidgetsApp(
1076
  ///     shortcuts: <ShortcutActivator, Intent>{
1077
  ///       ... WidgetsApp.defaultShortcuts,
1078
  ///       const SingleActivator(LogicalKeyboardKey.select): const ActivateIntent(),
1079 1080
  ///     },
  ///     color: const Color(0xFFFF0000),
1081
  ///     builder: (BuildContext context, Widget? child) {
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
  ///       return const Placeholder();
  ///     },
  ///   );
  /// }
  /// ```
  /// {@end-tool}
  ///
  /// {@template flutter.widgets.widgetsApp.shortcuts.seeAlso}
  /// See also:
  ///
1092 1093
  ///  * [SingleActivator], which defines shortcut key combination of a single
  ///    key and modifiers, such as "Delete" or "Control+C".
1094 1095 1096 1097 1098
  ///  * The [Shortcuts] widget, which defines a keyboard mapping.
  ///  * The [Actions] widget, which defines the mapping from intent to action.
  ///  * The [Intent] and [Action] classes, which allow definition of new
  ///    actions.
  /// {@endtemplate}
1099
  final Map<ShortcutActivator, Intent>? shortcuts;
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112

  /// {@template flutter.widgets.widgetsApp.actions}
  /// The default map of intent keys to actions for the application.
  ///
  /// By default, this is the output of [WidgetsApp.defaultActions], called with
  /// [defaultTargetPlatform]. Specifying [actions] for an app overrides the
  /// default, so if you wish to modify the default [actions], you can call
  /// [WidgetsApp.defaultActions] and modify the resulting map, passing it as
  /// the [actions] for this app. You may also add to the bindings, or override
  /// specific bindings for a widget subtree, by adding your own [Actions]
  /// widget.
  /// {@endtemplate}
  ///
1113
  /// {@tool snippet}
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
  /// This example shows how to add a single action handling an
  /// [ActivateAction] to the default actions without needing to
  /// add your own [Actions] widget.
  ///
  /// Alternatively, you could insert a [Actions] widget with just the mapping
  /// you want to add between the [WidgetsApp] and its child and get the same
  /// effect.
  ///
  /// ```dart
  /// Widget build(BuildContext context) {
  ///   return WidgetsApp(
1125
  ///     actions: <Type, Action<Intent>>{
1126
  ///       ... WidgetsApp.defaultActions,
1127
  ///       ActivateAction: CallbackAction<Intent>(
1128
  ///         onInvoke: (Intent intent) {
1129
  ///           // Do something here...
1130
  ///           return null;
1131 1132 1133 1134
  ///         },
  ///       ),
  ///     },
  ///     color: const Color(0xFFFF0000),
1135
  ///     builder: (BuildContext context, Widget? child) {
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
  ///       return const Placeholder();
  ///     },
  ///   );
  /// }
  /// ```
  /// {@end-tool}
  ///
  /// {@template flutter.widgets.widgetsApp.actions.seeAlso}
  /// See also:
  ///
  ///  * The [shortcuts] parameter, which defines the default set of shortcuts
  ///    for the application.
  ///  * The [Shortcuts] widget, which defines a keyboard mapping.
  ///  * The [Actions] widget, which defines the mapping from intent to action.
  ///  * The [Intent] and [Action] classes, which allow definition of new
  ///    actions.
  /// {@endtemplate}
1153
  final Map<Type, Action<Intent>>? actions;
1154

1155 1156 1157 1158 1159 1160
  /// {@template flutter.widgets.widgetsApp.restorationScopeId}
  /// The identifier to use for state restoration of this app.
  ///
  /// Providing a restoration ID inserts a [RootRestorationScope] into the
  /// widget hierarchy, which enables state restoration for descendant widgets.
  ///
1161 1162 1163 1164
  /// Providing a restoration ID also enables the [Navigator] or [Router] built
  /// by the [WidgetsApp] to restore its state (i.e. to restore the history
  /// stack of active [Route]s). See the documentation on [Navigator] for more
  /// details around state restoration of [Route]s.
1165 1166 1167 1168 1169 1170 1171 1172
  ///
  /// See also:
  ///
  ///  * [RestorationManager], which explains how state restoration works in
  ///    Flutter.
  /// {@endtemplate}
  final String? restorationScopeId;

1173 1174 1175 1176 1177 1178 1179 1180
  /// {@template flutter.widgets.widgetsApp.useInheritedMediaQuery}
  /// If true, an inherited MediaQuery will be used. If one is not available,
  /// or this is false, one will be built from the window.
  ///
  /// Cannot be null, defaults to false.
  /// {@endtemplate}
  final bool useInheritedMediaQuery;

1181 1182
  /// If true, forces the performance overlay to be visible in all instances.
  ///
1183
  /// Used by the `showPerformanceOverlay` observatory extension.
1184 1185
  static bool showPerformanceOverlayOverride = false;

1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
  /// If true, forces the widget inspector to be visible.
  ///
  /// Used by the `debugShowWidgetInspector` debugging extension.
  ///
  /// The inspector allows you to select a location on your device or emulator
  /// and view what widgets and render objects associated with it. An outline of
  /// the selected widget and some summary information is shown on device and
  /// more detailed information is shown in the IDE or Observatory.
  static bool debugShowWidgetInspectorOverride = false;

1196 1197
  /// If false, prevents the debug banner from being visible.
  ///
1198
  /// Used by the `debugAllowBanner` observatory extension.
1199 1200 1201 1202 1203
  ///
  /// This is how `flutter run` turns off the banner when you take a screen shot
  /// with "s".
  static bool debugAllowBannerOverride = true;

1204
  static const Map<ShortcutActivator, Intent> _defaultShortcuts = <ShortcutActivator, Intent>{
1205
    // Activation
1206
    SingleActivator(LogicalKeyboardKey.enter): ActivateIntent(),
1207
    SingleActivator(LogicalKeyboardKey.numpadEnter): ActivateIntent(),
1208 1209
    SingleActivator(LogicalKeyboardKey.space): ActivateIntent(),
    SingleActivator(LogicalKeyboardKey.gameButtonA): ActivateIntent(),
1210

1211
    // Dismissal
1212
    SingleActivator(LogicalKeyboardKey.escape): DismissIntent(),
1213

1214
    // Keyboard traversal.
1215 1216 1217 1218 1219 1220
    SingleActivator(LogicalKeyboardKey.tab): NextFocusIntent(),
    SingleActivator(LogicalKeyboardKey.tab, shift: true): PreviousFocusIntent(),
    SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent(TraversalDirection.left),
    SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent(TraversalDirection.right),
    SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down),
    SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up),
1221 1222

    // Scrolling
1223 1224 1225 1226 1227 1228
    SingleActivator(LogicalKeyboardKey.arrowUp, control: true): ScrollIntent(direction: AxisDirection.up),
    SingleActivator(LogicalKeyboardKey.arrowDown, control: true): ScrollIntent(direction: AxisDirection.down),
    SingleActivator(LogicalKeyboardKey.arrowLeft, control: true): ScrollIntent(direction: AxisDirection.left),
    SingleActivator(LogicalKeyboardKey.arrowRight, control: true): ScrollIntent(direction: AxisDirection.right),
    SingleActivator(LogicalKeyboardKey.pageUp): ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page),
    SingleActivator(LogicalKeyboardKey.pageDown): ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page),
1229 1230 1231
  };

  // Default shortcuts for the web platform.
1232
  static const Map<ShortcutActivator, Intent> _defaultWebShortcuts = <ShortcutActivator, Intent>{
1233
    // Activation
1234
    SingleActivator(LogicalKeyboardKey.space): PrioritizedIntents(
1235 1236 1237
      orderedIntents: <Intent>[
        ActivateIntent(),
        ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page),
1238
      ],
1239
    ),
1240
    // On the web, enter activates buttons, but not other controls.
1241
    SingleActivator(LogicalKeyboardKey.enter): ButtonActivateIntent(),
1242
    SingleActivator(LogicalKeyboardKey.numpadEnter): ButtonActivateIntent(),
1243

1244
    // Dismissal
1245
    SingleActivator(LogicalKeyboardKey.escape): DismissIntent(),
1246

1247
    // Keyboard traversal.
1248 1249
    SingleActivator(LogicalKeyboardKey.tab): NextFocusIntent(),
    SingleActivator(LogicalKeyboardKey.tab, shift: true): PreviousFocusIntent(),
1250 1251

    // Scrolling
1252 1253 1254 1255 1256 1257
    SingleActivator(LogicalKeyboardKey.arrowUp): ScrollIntent(direction: AxisDirection.up),
    SingleActivator(LogicalKeyboardKey.arrowDown): ScrollIntent(direction: AxisDirection.down),
    SingleActivator(LogicalKeyboardKey.arrowLeft): ScrollIntent(direction: AxisDirection.left),
    SingleActivator(LogicalKeyboardKey.arrowRight): ScrollIntent(direction: AxisDirection.right),
    SingleActivator(LogicalKeyboardKey.pageUp): ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page),
    SingleActivator(LogicalKeyboardKey.pageDown): ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page),
1258 1259 1260
  };

  // Default shortcuts for the macOS platform.
1261
  static const Map<ShortcutActivator, Intent> _defaultAppleOsShortcuts = <ShortcutActivator, Intent>{
1262
    // Activation
1263
    SingleActivator(LogicalKeyboardKey.enter): ActivateIntent(),
1264
    SingleActivator(LogicalKeyboardKey.numpadEnter): ActivateIntent(),
1265
    SingleActivator(LogicalKeyboardKey.space): ActivateIntent(),
1266

1267
    // Dismissal
1268
    SingleActivator(LogicalKeyboardKey.escape): DismissIntent(),
1269

1270
    // Keyboard traversal
1271 1272 1273 1274 1275 1276
    SingleActivator(LogicalKeyboardKey.tab): NextFocusIntent(),
    SingleActivator(LogicalKeyboardKey.tab, shift: true): PreviousFocusIntent(),
    SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent(TraversalDirection.left),
    SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent(TraversalDirection.right),
    SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down),
    SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up),
1277 1278

    // Scrolling
1279 1280 1281 1282 1283 1284
    SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): ScrollIntent(direction: AxisDirection.up),
    SingleActivator(LogicalKeyboardKey.arrowDown, meta: true): ScrollIntent(direction: AxisDirection.down),
    SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true): ScrollIntent(direction: AxisDirection.left),
    SingleActivator(LogicalKeyboardKey.arrowRight, meta: true): ScrollIntent(direction: AxisDirection.right),
    SingleActivator(LogicalKeyboardKey.pageUp): ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page),
    SingleActivator(LogicalKeyboardKey.pageDown): ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page),
1285 1286 1287 1288 1289 1290
  };

  /// Generates the default shortcut key bindings based on the
  /// [defaultTargetPlatform].
  ///
  /// Used by [WidgetsApp] to assign a default value to [WidgetsApp.shortcuts].
1291
  static Map<ShortcutActivator, Intent> get defaultShortcuts {
1292 1293 1294 1295 1296 1297 1298
    if (kIsWeb) {
      return _defaultWebShortcuts;
    }

    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
1299 1300
      case TargetPlatform.linux:
      case TargetPlatform.windows:
1301 1302
        return _defaultShortcuts;
      case TargetPlatform.iOS:
1303 1304
      case TargetPlatform.macOS:
        return _defaultAppleOsShortcuts;
1305 1306 1307 1308
    }
  }

  /// The default value of [WidgetsApp.actions].
1309 1310
  static Map<Type, Action<Intent>> defaultActions = <Type, Action<Intent>>{
    DoNothingIntent: DoNothingAction(),
1311
    DoNothingAndStopPropagationIntent: DoNothingAction(consumesKey: false),
1312 1313 1314 1315 1316
    RequestFocusIntent: RequestFocusAction(),
    NextFocusIntent: NextFocusAction(),
    PreviousFocusIntent: PreviousFocusAction(),
    DirectionalFocusIntent: DirectionalFocusAction(),
    ScrollIntent: ScrollAction(),
1317
    PrioritizedIntents: PrioritizedAction(),
1318
    VoidCallbackIntent: VoidCallbackAction(),
1319 1320
  };

1321
  @override
1322
  State<WidgetsApp> createState() => _WidgetsAppState();
1323 1324
}

1325
class _WidgetsAppState extends State<WidgetsApp> with WidgetsBindingObserver {
1326
  // STATE LIFECYCLE
1327

1328 1329 1330
  // If window.defaultRouteName isn't '/', we should assume it was set
  // intentionally via `setInitialRoute`, and should override whatever is in
  // [widget.initialRoute].
1331 1332 1333
  String get _initialRouteName => WidgetsBinding.instance.platformDispatcher.defaultRouteName != Navigator.defaultRouteName
    ? WidgetsBinding.instance.platformDispatcher.defaultRouteName
    : widget.initialRoute ?? WidgetsBinding.instance.platformDispatcher.defaultRouteName;
1334

1335
  @override
1336 1337
  void initState() {
    super.initState();
1338
    _updateRouting();
1339
    _locale = _resolveLocales(WidgetsBinding.instance.platformDispatcher.locales, widget.supportedLocales);
1340
    WidgetsBinding.instance.addObserver(this);
1341 1342
  }

1343 1344 1345
  @override
  void didUpdateWidget(WidgetsApp oldWidget) {
    super.didUpdateWidget(oldWidget);
1346
    _updateRouting(oldWidget: oldWidget);
1347 1348
  }

1349
  @override
1350
  void dispose() {
1351
    WidgetsBinding.instance.removeObserver(this);
1352
    _defaultRouteInformationProvider?.dispose();
1353 1354 1355
    super.dispose();
  }

1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
  void _clearRouterResource() {
    _defaultRouteInformationProvider?.dispose();
    _defaultRouteInformationProvider = null;
    _defaultBackButtonDispatcher = null;
  }

  void _clearNavigatorResource() {
    _navigator = null;
  }

1366
  void _updateRouting({WidgetsApp? oldWidget}) {
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
    if (_usesRouterWithDelegates) {
      assert(!_usesNavigator && !_usesRouterWithConfig);
      _clearNavigatorResource();
      if (widget.routeInformationProvider == null && widget.routeInformationParser != null) {
        _defaultRouteInformationProvider ??= PlatformRouteInformationProvider(
          initialRouteInformation: RouteInformation(
            location: _initialRouteName,
          ),
        );
      } else {
1377 1378 1379
        _defaultRouteInformationProvider?.dispose();
        _defaultRouteInformationProvider = null;
      }
1380 1381 1382 1383
      if (widget.backButtonDispatcher == null) {
        _defaultBackButtonDispatcher ??= RootBackButtonDispatcher();
      }

1384
    } else if (_usesNavigator) {
1385 1386
      assert(!_usesRouterWithDelegates && !_usesRouterWithConfig);
      _clearRouterResource();
1387
      if (_navigator == null || widget.navigatorKey != oldWidget!.navigatorKey) {
1388 1389 1390 1391
        _navigator = widget.navigatorKey ?? GlobalObjectKey<NavigatorState>(this);
      }
      assert(_navigator != null);
    } else {
1392 1393 1394 1395
      assert(widget.builder != null || _usesRouterWithConfig);
      assert(!_usesRouterWithDelegates && !_usesNavigator);
      _clearRouterResource();
      _clearNavigatorResource();
1396 1397 1398 1399 1400
    }
    // If we use a navigator, we have a navigator key.
    assert(_usesNavigator == (_navigator != null));
  }

1401 1402
  bool get _usesRouterWithDelegates => widget.routerDelegate != null;
  bool get _usesRouterWithConfig => widget.routerConfig != null;
1403 1404 1405 1406
  bool get _usesNavigator => widget.home != null
      || (widget.routes?.isNotEmpty ?? false)
      || widget.onGenerateRoute != null
      || widget.onUnknownRoute != null;
1407 1408

  // ROUTER
1409

1410 1411
  RouteInformationProvider? get _effectiveRouteInformationProvider => widget.routeInformationProvider ?? _defaultRouteInformationProvider;
  PlatformRouteInformationProvider? _defaultRouteInformationProvider;
1412 1413
  BackButtonDispatcher get _effectiveBackButtonDispatcher => widget.backButtonDispatcher ?? _defaultBackButtonDispatcher!;
  RootBackButtonDispatcher? _defaultBackButtonDispatcher;
1414

1415 1416
  // NAVIGATOR

1417
  GlobalKey<NavigatorState>? _navigator;
1418

1419 1420 1421 1422 1423
  Route<dynamic>? _onGenerateRoute(RouteSettings settings) {
    final String? name = settings.name;
    final WidgetBuilder? pageContentBuilder = name == Navigator.defaultRouteName && widget.home != null
        ? (BuildContext context) => widget.home!
        : widget.routes![name];
1424 1425

    if (pageContentBuilder != null) {
1426 1427
      assert(
        widget.pageRouteBuilder != null,
1428
        'The default onGenerateRoute handler for WidgetsApp must have a '
1429 1430
        'pageRouteBuilder set if the home or routes properties are set.',
      );
1431
      final Route<dynamic> route = widget.pageRouteBuilder!<dynamic>(
1432
        settings,
1433
        pageContentBuilder,
1434
      );
1435
      assert(route != null, 'The pageRouteBuilder for WidgetsApp must return a valid non-null Route.');
1436
      return route;
1437
    }
1438
    if (widget.onGenerateRoute != null) {
1439
      return widget.onGenerateRoute!(settings);
1440
    }
1441 1442 1443 1444 1445 1446 1447 1448
    return null;
  }

  Route<dynamic> _onUnknownRoute(RouteSettings settings) {
    assert(() {
      if (widget.onUnknownRoute == null) {
        throw FlutterError(
          'Could not find a generator for route $settings in the $runtimeType.\n'
1449 1450
          'Make sure your root app widget has provided a way to generate \n'
          'this route.\n'
1451 1452 1453 1454 1455 1456 1457
          'Generators for routes are searched for in the following order:\n'
          ' 1. For the "/" route, the "home" property, if non-null, is used.\n'
          ' 2. Otherwise, the "routes" table is used, if it has an entry for '
          'the route.\n'
          ' 3. Otherwise, onGenerateRoute is called. It should return a '
          'non-null value for any valid route not handled by "home" and "routes".\n'
          ' 4. Finally if all else fails onUnknownRoute is called.\n'
1458
          'Unfortunately, onUnknownRoute was not set.',
1459 1460 1461 1462
        );
      }
      return true;
    }());
1463
    final Route<dynamic>? result = widget.onUnknownRoute!(settings);
1464 1465
    assert(() {
      if (result == null) {
1466 1467 1468 1469
        throw FlutterError(
          'The onUnknownRoute callback returned null.\n'
          'When the $runtimeType requested the route $settings from its '
          'onUnknownRoute callback, the callback returned null. Such callbacks '
1470
          'must never return null.',
1471
        );
1472 1473 1474
      }
      return true;
    }());
1475
    return result!;
1476 1477
  }

1478
  // On Android: the user has pressed the back button.
1479
  @override
1480
  Future<bool> didPopRoute() async {
1481
    assert(mounted);
1482 1483
    // The back button dispatcher should handle the pop route if we use a
    // router.
1484
    if (_usesRouterWithDelegates) {
1485
      return false;
1486
    }
1487

1488
    final NavigatorState? navigator = _navigator?.currentState;
1489
    if (navigator == null) {
1490
      return false;
1491
    }
1492
    return navigator.maybePop();
1493 1494
  }

1495 1496 1497
  @override
  Future<bool> didPushRoute(String route) async {
    assert(mounted);
1498 1499
    // The route name provider should handle the push route if we uses a
    // router.
1500
    if (_usesRouterWithDelegates) {
1501
      return false;
1502
    }
1503

1504
    final NavigatorState? navigator = _navigator?.currentState;
1505
    if (navigator == null) {
1506
      return false;
1507
    }
1508 1509 1510 1511
    navigator.pushNamed(route);
    return true;
  }

1512 1513
  // LOCALIZATION

1514
  /// This is the resolved locale, and is one of the supportedLocales.
1515
  Locale? _locale;
1516

1517
  Locale _resolveLocales(List<Locale>? preferredLocales, Iterable<Locale> supportedLocales) {
1518 1519
    // Attempt to use localeListResolutionCallback.
    if (widget.localeListResolutionCallback != null) {
1520
      final Locale? locale = widget.localeListResolutionCallback!(preferredLocales, widget.supportedLocales);
1521
      if (locale != null) {
1522
        return locale;
1523
      }
1524 1525
    }
    // localeListResolutionCallback failed, falling back to localeResolutionCallback.
1526
    if (widget.localeResolutionCallback != null) {
1527
      final Locale? locale = widget.localeResolutionCallback!(
1528 1529 1530
        preferredLocales != null && preferredLocales.isNotEmpty ? preferredLocales.first : null,
        widget.supportedLocales,
      );
1531
      if (locale != null) {
1532
        return locale;
1533
      }
1534
    }
1535 1536 1537 1538
    // Both callbacks failed, falling back to default algorithm.
    return basicLocaleListResolution(preferredLocales, supportedLocales);
  }

1539
  @override
1540
  void didChangeLocales(List<Locale>? locales) {
1541
    final Locale newLocale = _resolveLocales(locales, widget.supportedLocales);
1542
    if (newLocale != _locale) {
1543
      setState(() {
1544
        _locale = newLocale;
1545 1546 1547 1548
      });
    }
  }

1549
  // Combine the Localizations for Widgets with the ones contributed
1550 1551 1552
  // by the localizationsDelegates parameter, if any. Only the first delegate
  // of a particular LocalizationsDelegate.type is loaded so the
  // localizationsDelegate parameter can be used to override
1553
  // WidgetsLocalizations.delegate.
1554 1555 1556 1557 1558 1559
  Iterable<LocalizationsDelegate<dynamic>> get _localizationsDelegates {
    return <LocalizationsDelegate<dynamic>>[
      if (widget.localizationsDelegates != null)
        ...widget.localizationsDelegates!,
      DefaultWidgetsLocalizations.delegate,
    ];
1560 1561
  }

1562
  // BUILDER
1563

1564 1565 1566 1567
  bool _debugCheckLocalizations(Locale appLocale) {
    assert(() {
      final Set<Type> unsupportedTypes =
        _localizationsDelegates.map<Type>((LocalizationsDelegate<dynamic> delegate) => delegate.type).toSet();
1568
      for (final LocalizationsDelegate<dynamic> delegate in _localizationsDelegates) {
1569
        if (!unsupportedTypes.contains(delegate.type)) {
1570
          continue;
1571 1572
        }
        if (delegate.isSupported(appLocale)) {
1573
          unsupportedTypes.remove(delegate.type);
1574
        }
1575
      }
1576
      if (unsupportedTypes.isEmpty) {
1577
        return true;
1578
      }
1579

1580 1581 1582
      FlutterError.reportError(FlutterErrorDetails(
        exception: "Warning: This application's locale, $appLocale, is not supported by all of its localization delegates.",
        library: 'widgets',
1583 1584 1585
        informationCollector: () => <DiagnosticsNode>[
          for (final Type unsupportedType in unsupportedTypes)
            ErrorDescription(
1586
              '• A $unsupportedType delegate that supports the $appLocale locale was not found.',
1587 1588 1589
            ),
          ErrorSpacer(),
          if (unsupportedTypes.length == 1 && unsupportedTypes.single.toString() == 'CupertinoLocalizations')
1590 1591
            // We previously explicitly avoided checking for this class so it's not uncommon for applications
            // to have omitted importing the required delegate.
1592 1593 1594 1595 1596 1597 1598 1599 1600
            ...<DiagnosticsNode>[
              ErrorHint(
                'If the application is built using GlobalMaterialLocalizations.delegate, consider using '
                'GlobalMaterialLocalizations.delegates (plural) instead, as that will automatically declare '
                'the appropriate Cupertino localizations.'
              ),
              ErrorSpacer(),
            ],
          ErrorHint(
1601
            'The declared supported locales for this app are: ${widget.supportedLocales.join(", ")}'
1602 1603 1604
          ),
          ErrorSpacer(),
          ErrorDescription(
1605 1606 1607
            'See https://flutter.dev/tutorials/internationalization/ for more '
            "information about configuring an app's locale, supportedLocales, "
            'and localizationsDelegates parameters.',
1608 1609
          ),
        ],
1610
      ));
1611 1612 1613 1614 1615
      return true;
    }());
    return true;
  }

1616
  @override
1617
  Widget build(BuildContext context) {
1618
    Widget? routing;
1619
    if (_usesRouterWithDelegates) {
1620
      routing = Router<Object>(
1621
        restorationScopeId: 'router',
1622 1623
        routeInformationProvider: _effectiveRouteInformationProvider,
        routeInformationParser: widget.routeInformationParser,
1624
        routerDelegate: widget.routerDelegate!,
1625
        backButtonDispatcher: _effectiveBackButtonDispatcher,
1626
      );
1627
    } else if (_usesNavigator) {
1628
      assert(_navigator != null);
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
      routing = FocusScope(
        debugLabel: 'Navigator Scope',
        autofocus: true,
        child: Navigator(
          restorationScopeId: 'nav',
          key: _navigator,
          initialRoute: _initialRouteName,
          onGenerateRoute: _onGenerateRoute,
          onGenerateInitialRoutes: widget.onGenerateInitialRoutes == null
            ? Navigator.defaultGenerateInitialRoutes
            : (NavigatorState navigator, String initialRouteName) {
              return widget.onGenerateInitialRoutes!(initialRouteName);
            },
          onUnknownRoute: _onUnknownRoute,
          observers: widget.navigatorObservers!,
          reportsRouteUpdateToEngine: true,
        ),
1646
      );
1647 1648 1649 1650 1651
    } else if (_usesRouterWithConfig) {
      routing = Router<Object>.withConfig(
        restorationScopeId: 'router',
        config: widget.routerConfig!,
      );
1652 1653 1654 1655
    }

    Widget result;
    if (widget.builder != null) {
1656
      result = Builder(
1657
        builder: (BuildContext context) {
1658
          return widget.builder!(context, routing);
1659 1660 1661
        },
      );
    } else {
1662
      assert(routing != null);
1663
      result = routing!;
1664
    }
1665

1666
    if (widget.textStyle != null) {
1667
      result = DefaultTextStyle(
1668
        style: widget.textStyle!,
1669
        child: result,
Ian Hickson's avatar
Ian Hickson committed
1670 1671
      );
    }
1672

1673
    PerformanceOverlay? performanceOverlay;
1674 1675
    // We need to push a performance overlay if any of the display or checkerboarding
    // options are set.
1676
    if (widget.showPerformanceOverlay || WidgetsApp.showPerformanceOverlayOverride) {
1677
      performanceOverlay = PerformanceOverlay.allEnabled(
1678 1679
        checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages,
        checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers,
1680 1681
      );
    } else if (widget.checkerboardRasterCacheImages || widget.checkerboardOffscreenLayers) {
1682
      performanceOverlay = PerformanceOverlay(
1683 1684
        checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages,
        checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers,
1685
      );
1686 1687
    }
    if (performanceOverlay != null) {
1688
      result = Stack(
1689 1690
        children: <Widget>[
          result,
1691
          Positioned(top: 0.0, left: 0.0, right: 0.0, child: performanceOverlay),
1692
        ],
1693 1694
      );
    }
1695

1696
    if (widget.showSemanticsDebugger) {
1697
      result = SemanticsDebugger(
1698
        child: result,
1699 1700
      );
    }
1701

1702
    assert(() {
1703
      if (widget.debugShowWidgetInspector || WidgetsApp.debugShowWidgetInspectorOverride) {
1704
        result = WidgetInspector(
1705
          selectButtonBuilder: widget.inspectorSelectButtonBuilder,
1706
          child: result,
1707 1708
        );
      }
1709
      if (widget.debugShowCheckedModeBanner && WidgetsApp.debugAllowBannerOverride) {
1710
        result = CheckedModeBanner(
1711
          child: result,
1712 1713 1714
        );
      }
      return true;
1715
    }());
1716

1717
    final Widget title;
1718
    if (widget.onGenerateTitle != null) {
1719
      title = Builder(
1720
        // This Builder exists to provide a context below the Localizations widget.
1721
        // The onGenerateTitle callback can refer to Localizations via its context
1722 1723
        // parameter.
        builder: (BuildContext context) {
1724
          final String title = widget.onGenerateTitle!(context);
1725
          assert(title != null, 'onGenerateTitle must return a non-null String');
1726
          return Title(
1727
            title: title,
1728
            color: widget.color.withOpacity(1.0),
1729 1730 1731 1732 1733
            child: result,
          );
        },
      );
    } else {
1734
      title = Title(
1735
        title: widget.title,
1736
        color: widget.color.withOpacity(1.0),
1737 1738 1739 1740
        child: result,
      );
    }

1741
    final Locale appLocale = widget.locale != null
1742 1743
      ? _resolveLocales(<Locale>[widget.locale!], widget.supportedLocales)
      : _locale!;
1744 1745

    assert(_debugCheckLocalizations(appLocale));
1746

1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
    Widget child = Localizations(
      locale: appLocale,
      delegates: _localizationsDelegates.toList(),
      child: title,
    );

    final MediaQueryData? data = MediaQuery.maybeOf(context);
    if (!widget.useInheritedMediaQuery || data == null) {
      child = MediaQuery.fromWindow(
        child: child,
      );
    }

1760 1761
    return RootRestorationScope(
      restorationId: widget.restorationScopeId,
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
      child: SharedAppData(
        child: Shortcuts(
          debugLabel: '<Default WidgetsApp Shortcuts>',
          shortcuts: widget.shortcuts ?? WidgetsApp.defaultShortcuts,
          // DefaultTextEditingShortcuts is nested inside Shortcuts so that it can
          // fall through to the defaultShortcuts.
          child: DefaultTextEditingShortcuts(
            child: Actions(
              actions: widget.actions ?? WidgetsApp.defaultActions,
              child: FocusTraversalGroup(
                policy: ReadingOrderTraversalPolicy(),
1773 1774 1775 1776
                child: TapRegionSurface(
                  child: ShortcutRegistrar(
                    child: child,
                  ),
1777
                ),
1778
              ),
1779
            ),
1780
          ),
1781
        ),
1782 1783
      ),
    );
1784 1785
  }
}