app.dart 63.1 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 6
// @dart = 2.8

7
import 'dart:async';
8
import 'dart:collection' show HashMap;
9

10
import 'package:flutter/foundation.dart';
11
import 'package:flutter/rendering.dart';
12
import 'package:flutter/services.dart';
13

14
import 'actions.dart';
15
import 'banner.dart';
16 17
import 'basic.dart';
import 'binding.dart';
18
import 'focus_traversal.dart';
19
import 'framework.dart';
20
import 'localizations.dart';
21 22
import 'media_query.dart';
import 'navigator.dart';
23
import 'pages.dart';
24
import 'performance_overlay.dart';
25
import 'scrollable.dart';
26
import 'semantics_debugger.dart';
27
import 'shortcuts.dart';
28
import 'text.dart';
29
import 'title.dart';
30
import 'widget_inspector.dart';
31

32
export 'dart:ui' show Locale;
33

34 35 36 37 38 39 40 41 42
/// 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
43
/// received the locale information from the platform. The [supportedLocales] parameter
44 45 46 47 48 49 50 51 52
/// 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].
typedef LocaleListResolutionCallback = Locale Function(List<Locale> locales, Iterable<Locale> supportedLocales);

Dan Field's avatar
Dan Field committed
53
/// {@template flutter.widgets.widgetsApp.localeResolutionCallback}
54 55
/// The signature of [WidgetsApp.localeResolutionCallback].
///
56
/// It is recommended to provide a [LocaleListResolutionCallback] instead of a
57
/// [LocaleResolutionCallback] when possible, as [LocaleResolutionCallback] only
58
/// receives a subset of the information provided in [LocaleListResolutionCallback].
59 60
///
/// A [LocaleResolutionCallback] is responsible for computing the locale of the app's
61
/// [Localizations] object when the app starts and when user changes the default
62
/// locale for the device after [LocaleListResolutionCallback] fails or is not provided.
63
///
64 65 66
/// This callback is also used if the app is created with a specific locale using
/// the [new WidgetsApp] `locale` parameter.
///
67 68 69
/// 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
70
/// locales. If [locale] is null, then Flutter has not yet received the locale
71
/// information from the platform. The [supportedLocales] parameter is just the value of
72
/// [WidgetsApp.supportedLocales].
73 74 75 76 77
///
/// 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
78
/// {@endtemplate}
79
typedef LocaleResolutionCallback = Locale Function(Locale locale, Iterable<Locale> supportedLocales);
80

81 82 83
/// The signature of [WidgetsApp.onGenerateTitle].
///
/// Used to generate a value for the app's [Title.title], which the device uses
84
/// to identify the app for the user. The `context` includes the [WidgetsApp]'s
85 86 87 88
/// [Localizations] widget so that this method can be used to produce a
/// localized title.
///
/// This function must not return null.
89
typedef GenerateAppTitle = String Function(BuildContext context);
90

91 92 93
/// The signature of [WidgetsApp.pageRouteBuilder].
///
/// Creates a [PageRoute] using the given [RouteSettings] and [WidgetBuilder].
94
typedef PageRouteFactory = PageRoute<T> Function<T>(RouteSettings settings, WidgetBuilder builder);
95

96 97 98 99 100
/// The signature of [WidgetsApp.onGenerateInitialRoutes].
///
/// Creates a series of one or more initial routes.
typedef InitialRouteListFactory = List<Route<dynamic>> Function(String initialRoute);

101
/// A convenience widget that wraps a number of widgets that are commonly
Ian Hickson's avatar
Ian Hickson committed
102 103
/// required for an application.
///
104 105 106
/// One of the primary roles that [WidgetsApp] provides is binding the system
/// back button to popping the [Navigator] or quitting the application.
///
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
/// It is used by both [MaterialApp] and [CupertinoApp] to implement base
/// functionality for an app.
///
/// 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
///    running in checked mode.
///  * [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].
///  * [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.
128
class WidgetsApp extends StatefulWidget {
129 130
  /// Creates a widget that wraps a number of widgets that are commonly
  /// required for an application.
131
  ///
132 133
  /// The boolean arguments, [color], and [navigatorObservers] must not be null.
  ///
134 135 136 137 138 139 140 141 142 143 144
  /// 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
  ///  _not_ contain an entry for `'/'`.  Conversely, if [home] is omitted, [routes]
  /// _must_ contain an entry for `'/'`.
  ///
145 146 147 148 149 150 151 152 153 154 155
  /// If [home] or [routes] are not null, the routing implementation needs to know how
  /// appropriately build [PageRoutes]. This can be achieved by supplying the
  /// [pageRouteBuilder] parameter.  The [pageRouteBuilder] is used by [MaterialApp]
  /// 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
156 157 158 159 160 161 162 163 164 165 166
  /// [onGeneratedRoute] and [onUnknownRoute] parameters. These parameters correspond
  /// to [Navigator.onGenerateRoute] and [Navigator.onUnknownRoute]. If [home], [routes],
  /// and [builder] are null, or if they fail to create a requested route,
  /// [onGeneratedRoute] will be invoked.  If that fails, [onUnknownRoute] will be invoked.
  ///
  /// The [pageRouteBuilder] will create a [PageRoute] that wraps newly built routes.
  /// If the [builder] is non-null and the [onGenerateRoute] argument is null, then the
  /// [builder] will not be provided only with the context and the child widget, whereas
  /// the [pageRouteBuilder] will be provided with [RouteSettings]. If [onGenerateRoute]
  /// is not provided, [navigatorKey], [onUnknownRoute], [navigatorObservers], and
  /// [initialRoute] must have their default values, as they will have no effect.
167 168 169 170
  ///
  /// The `supportedLocales` argument must be a list of one or more elements.
  /// By default supportedLocales is `[const Locale('en', 'US')]`.
  WidgetsApp({ // can't be const because the asserts use methods on Iterable :-(
171
    Key key,
172
    this.navigatorKey,
173
    this.onGenerateRoute,
174
    this.onGenerateInitialRoutes,
175
    this.onUnknownRoute,
176
    this.navigatorObservers = const <NavigatorObserver>[],
177
    this.initialRoute,
178 179 180
    this.pageRouteBuilder,
    this.home,
    this.routes = const <String, WidgetBuilder>{},
181
    this.builder,
182
    this.title = '',
183
    this.onGenerateTitle,
184
    this.textStyle,
185
    @required this.color,
186 187
    this.locale,
    this.localizationsDelegates,
188
    this.localeListResolutionCallback,
189
    this.localeResolutionCallback,
190
    this.supportedLocales = const <Locale>[Locale('en', 'US')],
191 192 193 194 195 196
    this.showPerformanceOverlay = false,
    this.checkerboardRasterCacheImages = false,
    this.checkerboardOffscreenLayers = false,
    this.showSemanticsDebugger = false,
    this.debugShowWidgetInspector = false,
    this.debugShowCheckedModeBanner = true,
197
    this.inspectorSelectButtonBuilder,
198 199
    this.shortcuts,
    this.actions,
200
  }) : assert(navigatorObservers != null),
201
       assert(routes != null),
202 203 204
       assert(
         home == null ||
         onGenerateInitialRoutes == null,
205
         'If onGenerateInitialRoutes is specified, the home argument will be '
206 207
         'redundant.'
       ),
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
       assert(
         home == null ||
         !routes.containsKey(Navigator.defaultRouteName),
         'If the home property is specified, the routes table '
         'cannot include an entry for "/", since it would be redundant.'
       ),
       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 '
         'app is started with an intent that specifies an unknown route.'
       ),
       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 '
         '(null, null, and the empty list, respectively).'
       ),
246 247 248 249 250 251 252 253
       assert(
         builder != null ||
         onGenerateRoute != null ||
         pageRouteBuilder != null,
         'If neither builder nor onGenerateRoute are provided, the '
         'pageRouteBuilder must be specified so that the default handler '
         'will know what kind of PageRoute transition to build.'
       ),
254
       assert(title != null),
255
       assert(color != null),
256
       assert(supportedLocales != null && supportedLocales.isNotEmpty),
257 258
       assert(showPerformanceOverlay != null),
       assert(checkerboardRasterCacheImages != null),
259
       assert(checkerboardOffscreenLayers != null),
260
       assert(showSemanticsDebugger != null),
261
       assert(debugShowCheckedModeBanner != null),
262
       assert(debugShowWidgetInspector != null),
263
       super(key: key);
264

265
  /// {@template flutter.widgets.widgetsApp.navigatorKey}
266 267 268 269 270 271 272 273 274 275 276
  /// 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.
277
  ///
278 279
  /// The [Navigator] is only built if [onGenerateRoute] is not null; if it is
  /// null, [navigatorKey] must also be null.
280
  /// {@endtemplate}
281
  final GlobalKey<NavigatorState> navigatorKey;
282

xster's avatar
xster committed
283
  /// {@template flutter.widgets.widgetsApp.onGenerateRoute}
284
  /// The route generator callback used when the app is navigated to a
Ian Hickson's avatar
Ian Hickson committed
285
  /// named route.
286 287 288 289 290 291 292 293
  ///
  /// 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.
294 295 296 297 298 299
  ///
  /// 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
300
  /// {@endtemplate}
301
  ///
302 303 304
  /// 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.
305 306
  final RouteFactory onGenerateRoute;

307 308 309 310 311 312 313 314 315 316
  /// {@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}
  final InitialRouteListFactory onGenerateInitialRoutes;

317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
  /// The [PageRoute] generator callback used when the app is navigated to a
  /// named route.
  ///
  /// This callback can be used, for example, to specify that a [MaterialPageRoute]
  /// or a [CupertinoPageRoute] should be used for building page transitions.
  final PageRouteFactory pageRouteBuilder;

  /// {@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).
350
  /// {@endtemplate}
351 352 353 354 355 356 357 358 359 360 361 362 363
  ///
  /// 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.
  final Widget home;

  /// 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
  /// [WidgetBuilder] is used to construct a [PageRoute] specified by
  /// [pageRouteBuilder] to perform an appropriate transition, including [Hero]
  /// animations, to the new route.
364
  ///
365 366 367 368 369 370 371 372 373 374 375 376 377 378
  /// {@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.
379
  /// {@endtemplate}
380 381 382 383 384 385
  ///
  /// 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.
  final Map<String, WidgetBuilder> routes;

xster's avatar
xster committed
386
  /// {@template flutter.widgets.widgetsApp.onUnknownRoute}
387 388 389
  /// Called when [onGenerateRoute] fails to generate a route, except for the
  /// [initialRoute].
  ///
390 391 392 393 394 395
  /// 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.
396
  ///
397 398 399 400
  /// 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}
401 402
  final RouteFactory onUnknownRoute;

xster's avatar
xster committed
403 404
  /// {@template flutter.widgets.widgetsApp.initialRoute}
  /// The name of the first route to show, if a [Navigator] is built.
405
  ///
406 407 408
  /// Defaults to [Window.defaultRouteName], which may be overridden by the code
  /// that launched the application.
  ///
409 410 411 412 413
  /// If the route name starts with a slash and has multiple slashes in it, 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 three routes `/a`, `/a/b`, and
  /// `/a/b/c` loaded, in that order.
414
  ///
415 416 417 418 419 420
  /// 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.
  ///
421 422 423
  /// 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.
424
  ///
425 426 427 428 429
  /// 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.
430
  ///
431
  /// {@endtemplate}
432 433
  final String initialRoute;

xster's avatar
xster committed
434
  /// {@template flutter.widgets.widgetsApp.navigatorObservers}
435 436 437 438
  /// 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.
439
  ///
440 441 442 443
  /// 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}
444 445
  final List<NavigatorObserver> navigatorObservers;

xster's avatar
xster committed
446
  /// {@template flutter.widgets.widgetsApp.builder}
447 448 449 450 451 452 453 454 455 456 457 458 459 460
  /// A builder for inserting widgets above the [Navigator] but below the other
  /// widgets created by the [WidgetsApp] widget, or for replacing the
  /// [Navigator] entirely.
  ///
  /// 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
  /// the routes in the [Navigator].
  ///
  /// 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
461 462 463
  /// For specifically overriding the [title] with a value based on the
  /// [Localizations], consider [onGenerateTitle] instead.
  ///
464 465 466
  /// The [builder] callback is passed two arguments, the [BuildContext] (as
  /// `context`) and a [Navigator] widget (as `child`).
  ///
467 468 469
  /// If no routes are provided 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.
470
  ///
471 472 473 474 475 476
  /// If routes _are_ provided using one or more of those properties, 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 and the [navigatorKey], [home], [routes], [onGenerateRoute],
  /// [onUnknownRoute], [initialRoute], and [navigatorObservers] properties will
  /// have no effect.
477 478
  ///
  /// If [builder] is null, it is as if a builder was specified that returned
479 480 481 482 483 484 485 486
  /// 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]
  /// explicitly providing a [Navigator] of its own, widgets and APIs such as
  /// [Hero], [Navigator.push] and [Navigator.pop], will not function.
  /// {@endtemplate}
487 488
  final TransitionBuilder builder;

xster's avatar
xster committed
489
  /// {@template flutter.widgets.widgetsApp.title}
490 491 492
  /// 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
493 494 495
  /// 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.
496 497
  ///
  /// To provide a localized title instead, use [onGenerateTitle].
xster's avatar
xster committed
498
  /// {@endtemplate}
499 500
  final String title;

xster's avatar
xster committed
501
  /// {@template flutter.widgets.widgetsApp.onGenerateTitle}
502 503 504 505 506 507 508 509 510 511 512
  /// 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
513
  /// {@endtemplate}
514 515 516 517 518
  final GenerateAppTitle onGenerateTitle;

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

xster's avatar
xster committed
519
  /// {@template flutter.widgets.widgetsApp.color}
520 521 522 523 524
  /// 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
525
  /// {@endtemplate}
526 527
  final Color color;

xster's avatar
xster committed
528
  /// {@template flutter.widgets.widgetsApp.locale}
529 530 531 532
  /// 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.
533
  ///
534 535
  /// 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
536
  /// the first element of [supportedLocales].
xster's avatar
xster committed
537
  /// {@endtemplate}
538 539 540 541 542 543 544
  ///
  /// See also:
  ///
  ///  * [localeResolutionCallback], which can override the default
  ///    [supportedLocales] matching algorithm.
  ///  * [localizationsDelegates], which collectively define all of the localized
  ///    resources used by this app.
545 546
  final Locale locale;

xster's avatar
xster committed
547
  /// {@template flutter.widgets.widgetsApp.localizationsDelegates}
548 549 550 551
  /// 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
552
  /// {@endtemplate}
553
  final Iterable<LocalizationsDelegate<dynamic>> localizationsDelegates;
554

555
  /// {@template flutter.widgets.widgetsApp.localeListResolutionCallback}
556 557 558 559
  /// 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
560 561 562 563 564 565 566
  /// 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
  /// null or fail to resolve (return null), the a basic fallback algorithm will
  /// be used.
567
  ///
568
  /// The priority of each available fallback is:
569
  ///
570
  ///  1. [localeListResolutionCallback] is attempted first.
Dan Field's avatar
Dan Field committed
571 572 573
  ///  1. [localeResolutionCallback] is attempted second.
  ///  1. Flutter's basic resolution algorithm, as described in
  ///     [supportedLocales], is attempted last.
574 575
  ///
  /// Properly localized projects should provide a more advanced algorithm than
Dan Field's avatar
Dan Field committed
576 577 578
  /// 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))
579
  /// and is optimized for speed at the detriment of some uncommon edge-cases.
xster's avatar
xster committed
580
  /// {@endtemplate}
581
  ///
582 583 584
  /// This callback considers the entire list of preferred locales.
  ///
  /// This algorithm should be able to handle a null or empty list of preferred locales,
585
  /// which indicates Flutter has not yet received locale information from the platform.
586
  ///
587 588
  /// See also:
  ///
589
  ///  * [MaterialApp.localeListResolutionCallback], which sets the callback of the
590
  ///    [WidgetsApp] it creates.
591 592 593 594 595 596 597 598 599
  final LocaleListResolutionCallback localeListResolutionCallback;

  /// {@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
600
  /// Flutter has not yet received locale information from the platform.
601 602 603
  ///
  /// See also:
  ///
604
  ///  * [MaterialApp.localeResolutionCallback], which sets the callback of the
605
  ///    [WidgetsApp] it creates.
606 607
  final LocaleResolutionCallback localeResolutionCallback;

xster's avatar
xster committed
608
  /// {@template flutter.widgets.widgetsApp.supportedLocales}
609 610 611 612 613 614 615 616
  /// 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')]`.
  ///
617
  /// The order of the list matters. The default locale resolution algorithm,
Dan Field's avatar
Dan Field committed
618
  /// `basicLocaleListResolution`, attempts to match by the following priority:
619 620
  ///
  ///  1. [Locale.languageCode], [Locale.scriptCode], and [Locale.countryCode]
621 622 623 624 625
  ///  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
626 627 628 629 630 631 632 633 634 635
  ///
  /// 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
  /// `basicLocaleListResolution` is optimized for speed and does not implement
  /// a full algorithm (such as the one defined in
  /// [Unicode TR35](https://unicode.org/reports/tr35/#LanguageMatching)) that
  /// takes distances between languages into account.
636 637 638 639 640 641
  ///
  /// 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
642 643
  /// 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
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
  /// 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
  /// supportedLocales: [
  ///   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
664
  /// {@endtemplate}
665 666 667 668 669 670 671
  ///
  /// 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.
672
  ///  * [localizationsDelegates], which collectively define all of the localized
673 674 675
  ///    resources used by this app.
  final Iterable<Locale> supportedLocales;

676
  /// Turns on a performance overlay.
xster's avatar
xster committed
677 678 679
  ///
  /// See also:
  ///
680
  ///  * <https://flutter.dev/debugging/#performanceoverlay>
681 682
  final bool showPerformanceOverlay;

683
  /// Checkerboards raster cache images.
684 685
  ///
  /// See [PerformanceOverlay.checkerboardRasterCacheImages].
686 687
  final bool checkerboardRasterCacheImages;

688 689 690 691 692
  /// Checkerboards layers rendered to offscreen bitmaps.
  ///
  /// See [PerformanceOverlay.checkerboardOffscreenLayers].
  final bool checkerboardOffscreenLayers;

693 694 695 696
  /// Turns on an overlay that shows the accessibility information
  /// reported by the framework.
  final bool showSemanticsDebugger;

697 698 699 700 701 702 703 704 705 706 707
  /// Turns on an overlay that enables inspecting the widget tree.
  ///
  /// The inspector is only available in checked mode as it depends on
  /// [RenderObject.debugDescribeChildren] which should not be called outside of
  /// checked mode.
  final bool debugShowWidgetInspector;

  /// Builds the widget the [WidgetInspector] uses to switch between view and
  /// inspect modes.
  ///
  /// This lets [MaterialApp] to use a material button to toggle the inspector
708
  /// select mode without requiring [WidgetInspector] to depend on the
709 710 711
  /// material package.
  final InspectorSelectButtonBuilder inspectorSelectButtonBuilder;

xster's avatar
xster committed
712 713
  /// {@template flutter.widgets.widgetsApp.debugShowCheckedModeBanner}
  /// Turns on a little "DEBUG" banner in checked mode to indicate
714 715 716 717 718 719 720
  /// that the app is in checked mode. This is on by default (in
  /// checked mode), to turn it off, set the constructor argument to
  /// 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
721
  /// This banner is intended to deter people from complaining that your
722 723 724 725
  /// app is slow when it's in checked mode. In checked mode, Flutter
  /// enables a large number of expensive diagnostics to aid in
  /// development, and so performance in checked mode is not
  /// representative of what will happen in release mode.
xster's avatar
xster committed
726
  /// {@endtemplate}
727 728
  final bool debugShowCheckedModeBanner;

729 730 731 732 733 734
  /// {@template flutter.widgets.widgetsApp.shortcuts}
  /// The default map of keyboard shortcuts to intents for the application.
  ///
  /// By default, this is set to [WidgetsApp.defaultShortcuts].
  /// {@endtemplate}
  ///
735
  /// {@tool snippet}
736 737 738 739 740 741 742 743 744 745 746 747 748
  /// 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(
  ///     shortcuts: <LogicalKeySet, Intent>{
  ///       ... WidgetsApp.defaultShortcuts,
749
  ///       LogicalKeySet(LogicalKeyboardKey.select): const ActivateIntent(),
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
  ///     },
  ///     color: const Color(0xFFFF0000),
  ///     builder: (BuildContext context, Widget child) {
  ///       return const Placeholder();
  ///     },
  ///   );
  /// }
  /// ```
  /// {@end-tool}
  ///
  /// {@template flutter.widgets.widgetsApp.shortcuts.seeAlso}
  /// See also:
  ///
  ///  * [LogicalKeySet], a set of [LogicalKeyboardKey]s that make up the keys
  ///    for this map.
  ///  * 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}
  final Map<LogicalKeySet, Intent> shortcuts;

  /// {@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}
  ///
784
  /// {@tool snippet}
785 786 787 788 789 790 791 792 793 794 795
  /// 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(
796
  ///     actions: <Type, Action<Intent>>{
797
  ///       ... WidgetsApp.defaultActions,
798 799
  ///       ActivateAction: CallbackAction(
  ///         onInvoke: (Intent intent) {
800
  ///           // Do something here...
801
  ///           return null;
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
  ///         },
  ///       ),
  ///     },
  ///     color: const Color(0xFFFF0000),
  ///     builder: (BuildContext context, Widget child) {
  ///       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}
824
  final Map<Type, Action<Intent>> actions;
825

826 827
  /// If true, forces the performance overlay to be visible in all instances.
  ///
828
  /// Used by the `showPerformanceOverlay` observatory extension.
829 830
  static bool showPerformanceOverlayOverride = false;

831 832 833 834 835 836 837 838 839 840
  /// 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;

841 842
  /// If false, prevents the debug banner from being visible.
  ///
843
  /// Used by the `debugAllowBanner` observatory extension.
844 845 846 847 848
  ///
  /// This is how `flutter run` turns off the banner when you take a screen shot
  /// with "s".
  static bool debugAllowBannerOverride = true;

849 850
  static final Map<LogicalKeySet, Intent> _defaultShortcuts = <LogicalKeySet, Intent>{
    // Activation
851 852 853
    LogicalKeySet(LogicalKeyboardKey.enter): const ActivateIntent(),
    LogicalKeySet(LogicalKeyboardKey.space): const ActivateIntent(),
    LogicalKeySet(LogicalKeyboardKey.gameButtonA): const ActivateIntent(),
854

855 856 857 858
    // Dismissal
    LogicalKeySet(LogicalKeyboardKey.escape): const DismissIntent(),
    LogicalKeySet(LogicalKeyboardKey.gameButtonB): const ActivateIntent(),

859
    // Keyboard traversal.
860 861
    LogicalKeySet(LogicalKeyboardKey.tab): const NextFocusIntent(),
    LogicalKeySet(LogicalKeyboardKey.shift, LogicalKeyboardKey.tab): const PreviousFocusIntent(),
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
    LogicalKeySet(LogicalKeyboardKey.arrowLeft): const DirectionalFocusIntent(TraversalDirection.left),
    LogicalKeySet(LogicalKeyboardKey.arrowRight): const DirectionalFocusIntent(TraversalDirection.right),
    LogicalKeySet(LogicalKeyboardKey.arrowDown): const DirectionalFocusIntent(TraversalDirection.down),
    LogicalKeySet(LogicalKeyboardKey.arrowUp): const DirectionalFocusIntent(TraversalDirection.up),

    // Scrolling
    LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.arrowUp): const ScrollIntent(direction: AxisDirection.up),
    LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.arrowDown): const ScrollIntent(direction: AxisDirection.down),
    LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.arrowLeft): const ScrollIntent(direction: AxisDirection.left),
    LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.arrowRight): const ScrollIntent(direction: AxisDirection.right),
    LogicalKeySet(LogicalKeyboardKey.pageUp): const ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page),
    LogicalKeySet(LogicalKeyboardKey.pageDown): const ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page),
  };

  // Default shortcuts for the web platform.
  static final Map<LogicalKeySet, Intent> _defaultWebShortcuts = <LogicalKeySet, Intent>{
    // Activation
879
    LogicalKeySet(LogicalKeyboardKey.space): const ActivateIntent(),
880

881 882 883
    // Dismissal
    LogicalKeySet(LogicalKeyboardKey.escape): const DismissIntent(),

884
    // Keyboard traversal.
885 886
    LogicalKeySet(LogicalKeyboardKey.tab): const NextFocusIntent(),
    LogicalKeySet(LogicalKeyboardKey.shift, LogicalKeyboardKey.tab): const PreviousFocusIntent(),
887 888 889 890 891 892 893 894 895 896 897 898 899

    // Scrolling
    LogicalKeySet(LogicalKeyboardKey.arrowUp): const ScrollIntent(direction: AxisDirection.up),
    LogicalKeySet(LogicalKeyboardKey.arrowDown): const ScrollIntent(direction: AxisDirection.down),
    LogicalKeySet(LogicalKeyboardKey.arrowLeft): const ScrollIntent(direction: AxisDirection.left),
    LogicalKeySet(LogicalKeyboardKey.arrowRight): const ScrollIntent(direction: AxisDirection.right),
    LogicalKeySet(LogicalKeyboardKey.pageUp): const ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page),
    LogicalKeySet(LogicalKeyboardKey.pageDown): const ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page),
  };

  // Default shortcuts for the macOS platform.
  static final Map<LogicalKeySet, Intent> _defaultMacOsShortcuts = <LogicalKeySet, Intent>{
    // Activation
900 901
    LogicalKeySet(LogicalKeyboardKey.enter): const ActivateIntent(),
    LogicalKeySet(LogicalKeyboardKey.space): const ActivateIntent(),
902

903 904 905
    // Dismissal
    LogicalKeySet(LogicalKeyboardKey.escape): const DismissIntent(),

906
    // Keyboard traversal
907 908
    LogicalKeySet(LogicalKeyboardKey.tab): const NextFocusIntent(),
    LogicalKeySet(LogicalKeyboardKey.shift, LogicalKeyboardKey.tab): const PreviousFocusIntent(),
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
    LogicalKeySet(LogicalKeyboardKey.arrowLeft): const DirectionalFocusIntent(TraversalDirection.left),
    LogicalKeySet(LogicalKeyboardKey.arrowRight): const DirectionalFocusIntent(TraversalDirection.right),
    LogicalKeySet(LogicalKeyboardKey.arrowDown): const DirectionalFocusIntent(TraversalDirection.down),
    LogicalKeySet(LogicalKeyboardKey.arrowUp): const DirectionalFocusIntent(TraversalDirection.up),

    // Scrolling
    LogicalKeySet(LogicalKeyboardKey.meta, LogicalKeyboardKey.arrowUp): const ScrollIntent(direction: AxisDirection.up),
    LogicalKeySet(LogicalKeyboardKey.meta, LogicalKeyboardKey.arrowDown): const ScrollIntent(direction: AxisDirection.down),
    LogicalKeySet(LogicalKeyboardKey.meta, LogicalKeyboardKey.arrowLeft): const ScrollIntent(direction: AxisDirection.left),
    LogicalKeySet(LogicalKeyboardKey.meta, LogicalKeyboardKey.arrowRight): const ScrollIntent(direction: AxisDirection.right),
    LogicalKeySet(LogicalKeyboardKey.pageUp): const ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page),
    LogicalKeySet(LogicalKeyboardKey.pageDown): const ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page),
  };

  /// Generates the default shortcut key bindings based on the
  /// [defaultTargetPlatform].
  ///
  /// Used by [WidgetsApp] to assign a default value to [WidgetsApp.shortcuts].
  static Map<LogicalKeySet, Intent> get defaultShortcuts {
    if (kIsWeb) {
      return _defaultWebShortcuts;
    }

    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
935 936
      case TargetPlatform.linux:
      case TargetPlatform.windows:
937 938 939 940 941 942 943 944 945 946 947
        return _defaultShortcuts;
      case TargetPlatform.macOS:
        return _defaultMacOsShortcuts;
      case TargetPlatform.iOS:
        // No keyboard support on iOS yet.
        break;
    }
    return <LogicalKeySet, Intent>{};
  }

  /// The default value of [WidgetsApp.actions].
948 949 950 951 952 953 954
  static Map<Type, Action<Intent>> defaultActions = <Type, Action<Intent>>{
    DoNothingIntent: DoNothingAction(),
    RequestFocusIntent: RequestFocusAction(),
    NextFocusIntent: NextFocusAction(),
    PreviousFocusIntent: PreviousFocusAction(),
    DirectionalFocusIntent: DirectionalFocusAction(),
    ScrollIntent: ScrollAction(),
955 956
  };

957
  @override
958
  _WidgetsAppState createState() => _WidgetsAppState();
959 960
}

961
class _WidgetsAppState extends State<WidgetsApp> with WidgetsBindingObserver {
962
  // STATE LIFECYCLE
963

964
  @override
965 966
  void initState() {
    super.initState();
967
    _updateNavigator();
968
    _locale = _resolveLocales(WidgetsBinding.instance.window.locales, widget.supportedLocales);
969
    WidgetsBinding.instance.addObserver(this);
970 971
  }

972 973 974 975 976 977 978
  @override
  void didUpdateWidget(WidgetsApp oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.navigatorKey != oldWidget.navigatorKey)
      _updateNavigator();
  }

979
  @override
980
  void dispose() {
981
    WidgetsBinding.instance.removeObserver(this);
982 983 984
    super.dispose();
  }

985 986 987 988 989
  // NAVIGATOR

  GlobalKey<NavigatorState> _navigator;

  void _updateNavigator() {
990 991 992 993 994
    _navigator = widget.navigatorKey ?? GlobalObjectKey<NavigatorState>(this);
  }

  Route<dynamic> _onGenerateRoute(RouteSettings settings) {
    final String name = settings.name;
995 996 997 998 999
    final WidgetBuilder pageContentBuilder = name == Navigator.defaultRouteName && widget.home != null
        ? (BuildContext context) => widget.home
        : widget.routes[name];

    if (pageContentBuilder != null) {
1000 1001 1002
      assert(widget.pageRouteBuilder != null,
        'The default onGenerateRoute handler for WidgetsApp must have a '
        'pageRouteBuilder set if the home or routes properties are set.');
1003
      final Route<dynamic> route = widget.pageRouteBuilder<dynamic>(
1004
        settings,
1005
        pageContentBuilder,
1006 1007 1008 1009
      );
      assert(route != null,
        'The pageRouteBuilder for WidgetsApp must return a valid non-null Route.');
      return route;
1010
    }
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    if (widget.onGenerateRoute != null)
      return widget.onGenerateRoute(settings);
    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'
          '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'
          'Unfortunately, onUnknownRoute was not set.'
        );
      }
      return true;
    }());
    final Route<dynamic> result = widget.onUnknownRoute(settings);
    assert(() {
      if (result == null) {
1036 1037 1038 1039 1040 1041
        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 '
          'must never return null.'
        );
1042 1043 1044 1045
      }
      return true;
    }());
    return result;
1046 1047
  }

1048
  // On Android: the user has pressed the back button.
1049
  @override
1050
  Future<bool> didPopRoute() async {
1051
    assert(mounted);
1052 1053 1054
    final NavigatorState navigator = _navigator?.currentState;
    if (navigator == null)
      return false;
1055
    return await navigator.maybePop();
1056 1057
  }

1058 1059 1060
  @override
  Future<bool> didPushRoute(String route) async {
    assert(mounted);
1061 1062 1063
    final NavigatorState navigator = _navigator?.currentState;
    if (navigator == null)
      return false;
1064 1065 1066 1067
    navigator.pushNamed(route);
    return true;
  }

1068 1069
  // LOCALIZATION

1070
  /// This is the resolved locale, and is one of the supportedLocales.
1071 1072
  Locale _locale;

1073 1074 1075 1076 1077 1078 1079 1080
  Locale _resolveLocales(List<Locale> preferredLocales, Iterable<Locale> supportedLocales) {
    // Attempt to use localeListResolutionCallback.
    if (widget.localeListResolutionCallback != null) {
      final Locale locale = widget.localeListResolutionCallback(preferredLocales, widget.supportedLocales);
      if (locale != null)
        return locale;
    }
    // localeListResolutionCallback failed, falling back to localeResolutionCallback.
1081
    if (widget.localeResolutionCallback != null) {
1082 1083 1084 1085
      final Locale locale = widget.localeResolutionCallback(
        preferredLocales != null && preferredLocales.isNotEmpty ? preferredLocales.first : null,
        widget.supportedLocales,
      );
1086 1087 1088
      if (locale != null)
        return locale;
    }
1089 1090 1091 1092 1093 1094
    // Both callbacks failed, falling back to default algorithm.
    return basicLocaleListResolution(preferredLocales, supportedLocales);
  }

  /// The default locale resolution algorithm.
  ///
Dan Field's avatar
Dan Field committed
1095 1096 1097
  /// Custom resolution algorithms can be provided through
  /// [WidgetsApp.localeListResolutionCallback] or
  /// [WidgetsApp.localeResolutionCallback].
1098
  ///
Dan Field's avatar
Dan Field committed
1099 1100
  /// When no custom locale resolution algorithms are provided or if both fail
  /// to resolve, Flutter will default to calling this algorithm.
1101 1102 1103 1104
  ///
  /// This algorithm prioritizes speed at the cost of slightly less appropriate
  /// resolutions for edge cases.
  ///
Dan Field's avatar
Dan Field committed
1105
  /// This algorithm will resolve to the earliest preferred locale that
1106 1107 1108 1109
  /// 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
Dan Field's avatar
Dan Field committed
1110
  /// default (first) locale, the next preferred locale with a
1111
  /// perfect match can supersede the languageCode-only match if it exists.
1112
  ///
Dan Field's avatar
Dan Field committed
1113 1114
  /// When a preferredLocale matches more than one supported locale, it will
  /// resolve to the first matching locale listed in the supportedLocales.
1115
  ///
Dan Field's avatar
Dan Field committed
1116 1117
  /// When all preferred locales have been exhausted without a match, the first
  /// countryCode only match will be returned.
1118
  ///
Dan Field's avatar
Dan Field committed
1119 1120
  /// When no match at all is found, the first (default) locale in
  /// [supportedLocales] will be returned.
1121
  ///
1122 1123 1124
  /// To summarize, the main matching priority is:
  ///
  ///  1. [Locale.languageCode], [Locale.scriptCode], and [Locale.countryCode]
Dan Field's avatar
Dan Field committed
1125 1126 1127 1128 1129
  ///  1. [Locale.languageCode] and [Locale.scriptCode] only
  ///  1. [Locale.languageCode] and [Locale.countryCode] only
  ///  1. [Locale.languageCode] only (with caveats, see above)
  ///  1. [Locale.countryCode] only when all [preferredLocales] fail to match
  ///  1. Returns the first element of [supportedLocales] as a fallback
1130
  ///
1131 1132 1133 1134 1135 1136 1137 1138 1139
  /// 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).
  static 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) {
1140 1141
      return supportedLocales.first;
    }
1142 1143 1144 1145 1146 1147 1148
    // 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>();
1149
    for (final Locale locale in supportedLocales) {
1150 1151 1152 1153 1154 1155
      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;
    }
1156

1157 1158 1159 1160 1161
    // 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.
1162
    Locale matchesLanguageCode;
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    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) {
1180
        final Locale match = languageAndCountryLocales['${userLocale.languageCode}_${userLocale.countryCode}'];
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
        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,
1205
      // attempt to match by country only, as a user is likely to be familiar with a
1206 1207 1208 1209 1210 1211 1212
      // language from their listed country.
      if (matchesCountryCode == null && userLocale.countryCode != null) {
        match = countryLocales[userLocale.countryCode];
        if (match != null) {
          matchesCountryCode = match;
        }
      }
1213
    }
1214 1215
    // 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
1216
    // supported locale.
1217 1218
    final Locale resolvedLocale = matchesLanguageCode ?? matchesCountryCode ?? supportedLocales.first;
    return resolvedLocale;
1219 1220
  }

1221
  @override
1222 1223
  void didChangeLocales(List<Locale> locales) {
    final Locale newLocale = _resolveLocales(locales, widget.supportedLocales);
1224
    if (newLocale != _locale) {
1225
      setState(() {
1226
        _locale = newLocale;
1227 1228 1229 1230
      });
    }
  }

1231
  // Combine the Localizations for Widgets with the ones contributed
1232 1233 1234
  // 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
1235
  // WidgetsLocalizations.delegate.
1236 1237 1238
  Iterable<LocalizationsDelegate<dynamic>> get _localizationsDelegates sync* {
    if (widget.localizationsDelegates != null)
      yield* widget.localizationsDelegates;
1239
    yield DefaultWidgetsLocalizations.delegate;
1240 1241
  }

1242
  // BUILDER
1243

1244 1245 1246 1247
  bool _debugCheckLocalizations(Locale appLocale) {
    assert(() {
      final Set<Type> unsupportedTypes =
        _localizationsDelegates.map<Type>((LocalizationsDelegate<dynamic> delegate) => delegate.type).toSet();
1248
      for (final LocalizationsDelegate<dynamic> delegate in _localizationsDelegates) {
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
        if (!unsupportedTypes.contains(delegate.type))
          continue;
        if (delegate.isSupported(appLocale))
          unsupportedTypes.remove(delegate.type);
      }
      if (unsupportedTypes.isEmpty)
        return true;

      // Currently the Cupertino library only provides english localizations.
      // Remove this when https://github.com/flutter/flutter/issues/23847
      // is fixed.
      if (listEquals(unsupportedTypes.map((Type type) => type.toString()).toList(), <String>['CupertinoLocalizations']))
        return true;

      final StringBuffer message = StringBuffer();
      message.writeln('\u2550' * 8);
      message.writeln(
1266
        "Warning: This application's locale, $appLocale, is not supported by all of its\n"
1267 1268
        'localization delegates.'
      );
1269
      for (final Type unsupportedType in unsupportedTypes) {
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
        // Currently the Cupertino library only provides english localizations.
        // Remove this when https://github.com/flutter/flutter/issues/23847
        // is fixed.
        if (unsupportedType.toString() == 'CupertinoLocalizations')
          continue;
        message.writeln(
          '> A $unsupportedType delegate that supports the $appLocale locale was not found.'
        );
      }
      message.writeln(
1280
        'See https://flutter.dev/tutorials/internationalization/ for more\n'
1281
        "information about configuring an app's locale, supportedLocales,\n"
1282 1283 1284 1285 1286 1287 1288 1289 1290
        'and localizationsDelegates parameters.'
      );
      message.writeln('\u2550' * 8);
      debugPrint(message.toString());
      return true;
    }());
    return true;
  }

1291
  @override
1292
  Widget build(BuildContext context) {
1293 1294
    Widget navigator;
    if (_navigator != null) {
1295
      navigator = Navigator(
1296
        key: _navigator,
1297
        // If window.defaultRouteName isn't '/', we should assume it was set
1298 1299
        // intentionally via `setInitialRoute`, and should override whatever
        // is in [widget.initialRoute].
1300 1301 1302
        initialRoute: WidgetsBinding.instance.window.defaultRouteName != Navigator.defaultRouteName
            ? WidgetsBinding.instance.window.defaultRouteName
            : widget.initialRoute ?? WidgetsBinding.instance.window.defaultRouteName,
1303
        onGenerateRoute: _onGenerateRoute,
1304 1305 1306 1307 1308
        onGenerateInitialRoutes: widget.onGenerateInitialRoutes == null
          ? Navigator.defaultGenerateInitialRoutes
          : (NavigatorState navigator, String initialRouteName) {
            return widget.onGenerateInitialRoutes(initialRouteName);
          },
1309
        onUnknownRoute: _onUnknownRoute,
1310 1311 1312 1313 1314 1315
        observers: widget.navigatorObservers,
      );
    }

    Widget result;
    if (widget.builder != null) {
1316
      result = Builder(
1317 1318 1319 1320 1321 1322 1323 1324
        builder: (BuildContext context) {
          return widget.builder(context, navigator);
        },
      );
    } else {
      assert(navigator != null);
      result = navigator;
    }
1325

1326
    if (widget.textStyle != null) {
1327
      result = DefaultTextStyle(
1328
        style: widget.textStyle,
1329
        child: result,
Ian Hickson's avatar
Ian Hickson committed
1330 1331
      );
    }
1332 1333 1334 1335

    PerformanceOverlay performanceOverlay;
    // We need to push a performance overlay if any of the display or checkerboarding
    // options are set.
1336
    if (widget.showPerformanceOverlay || WidgetsApp.showPerformanceOverlayOverride) {
1337
      performanceOverlay = PerformanceOverlay.allEnabled(
1338 1339
        checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages,
        checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers,
1340 1341
      );
    } else if (widget.checkerboardRasterCacheImages || widget.checkerboardOffscreenLayers) {
1342
      performanceOverlay = PerformanceOverlay(
1343 1344
        checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages,
        checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers,
1345
      );
1346 1347
    }
    if (performanceOverlay != null) {
1348
      result = Stack(
1349 1350
        children: <Widget>[
          result,
1351
          Positioned(top: 0.0, left: 0.0, right: 0.0, child: performanceOverlay),
1352
        ],
1353 1354
      );
    }
1355

1356
    if (widget.showSemanticsDebugger) {
1357
      result = SemanticsDebugger(
1358
        child: result,
1359 1360
      );
    }
1361

1362
    assert(() {
1363
      if (widget.debugShowWidgetInspector || WidgetsApp.debugShowWidgetInspectorOverride) {
1364
        result = WidgetInspector(
1365 1366 1367 1368
          child: result,
          selectButtonBuilder: widget.inspectorSelectButtonBuilder,
        );
      }
1369
      if (widget.debugShowCheckedModeBanner && WidgetsApp.debugAllowBannerOverride) {
1370
        result = CheckedModeBanner(
1371
          child: result,
1372 1373 1374
        );
      }
      return true;
1375
    }());
1376

1377 1378
    Widget title;
    if (widget.onGenerateTitle != null) {
1379
      title = Builder(
1380
        // This Builder exists to provide a context below the Localizations widget.
1381
        // The onGenerateTitle callback can refer to Localizations via its context
1382 1383 1384 1385
        // parameter.
        builder: (BuildContext context) {
          final String title = widget.onGenerateTitle(context);
          assert(title != null, 'onGenerateTitle must return a non-null String');
1386
          return Title(
1387 1388 1389 1390 1391 1392 1393
            title: title,
            color: widget.color,
            child: result,
          );
        },
      );
    } else {
1394
      title = Title(
1395 1396 1397 1398 1399 1400
        title: widget.title,
        color: widget.color,
        child: result,
      );
    }

1401
    final Locale appLocale = widget.locale != null
1402
      ? _resolveLocales(<Locale>[widget.locale], widget.supportedLocales)
1403 1404 1405
      : _locale;

    assert(_debugCheckLocalizations(appLocale));
1406
    return Shortcuts(
1407
      shortcuts: widget.shortcuts ?? WidgetsApp.defaultShortcuts,
1408
      debugLabel: '<Default WidgetsApp Shortcuts>',
1409
      child: Actions(
1410
        actions: widget.actions ?? WidgetsApp.defaultActions,
1411
        child: FocusTraversalGroup(
1412 1413 1414 1415 1416 1417 1418
          policy: ReadingOrderTraversalPolicy(),
          child: _MediaQueryFromWindow(
            child: Localizations(
              locale: appLocale,
              delegates: _localizationsDelegates.toList(),
              child: title,
            ),
1419
          ),
1420
        ),
1421 1422
      ),
    );
1423 1424
  }
}
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486

/// Builds [MediaQuery] from `window` by listening to [WidgetsBinding].
///
/// It is performed in a standalone widget to rebuild **only** [MediaQuery] and
/// its dependents when `window` changes, instead of rebuilding the entire widget tree.
class _MediaQueryFromWindow extends StatefulWidget {
  const _MediaQueryFromWindow({Key key, this.child}) : super(key: key);

  final Widget child;

  @override
  _MediaQueryFromWindowsState createState() => _MediaQueryFromWindowsState();
}

class _MediaQueryFromWindowsState extends State<_MediaQueryFromWindow> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  // ACCESSIBILITY

  @override
  void didChangeAccessibilityFeatures() {
    setState(() {
      // The properties of window have changed. We use them in our build
      // function, so we need setState(), but we don't cache anything locally.
    });
  }

  // METRICS

  @override
  void didChangeMetrics() {
    setState(() {
      // The properties of window have changed. We use them in our build
      // function, so we need setState(), but we don't cache anything locally.
    });
  }

  @override
  void didChangeTextScaleFactor() {
    setState(() {
      // The textScaleFactor property of window has changed. We reference
      // window in our build function, so we need to call setState(), but
      // we don't need to cache anything locally.
    });
  }

  // RENDERING
  @override
  void didChangePlatformBrightness() {
    setState(() {
      // The platformBrightness property of window has changed. We reference
      // window in our build function, so we need to call setState(), but
      // we don't need to cache anything locally.
    });
  }

  @override
  Widget build(BuildContext context) {
1487 1488 1489 1490
    MediaQueryData data = MediaQueryData.fromWindow(WidgetsBinding.instance.window);
    if (!kReleaseMode) {
      data = data.copyWith(platformBrightness: debugBrightnessOverride);
    }
1491
    return MediaQuery(
1492
      data: data,
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
      child: widget.child,
    );
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}