app.dart 50.6 KB
Newer Older
1 2 3 4 5
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
6
import 'dart:collection' show HashMap;
7

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

11
import 'banner.dart';
12 13 14
import 'basic.dart';
import 'binding.dart';
import 'framework.dart';
15
import 'localizations.dart';
16 17
import 'media_query.dart';
import 'navigator.dart';
18
import 'pages.dart';
19 20
import 'performance_overlay.dart';
import 'semantics_debugger.dart';
21
import 'text.dart';
22
import 'title.dart';
23
import 'widget_inspector.dart';
24

25
export 'dart:ui' show Locale;
26

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
/// 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
/// recieved the locale information from the platform. The [supportedLocales] parameter
/// 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);

46 47
/// The signature of [WidgetsApp.localeResolutionCallback].
///
48
/// It is recommended to provide a [LocaleListResolutionCallback] instead of a
49 50
/// [LocaleResolutionCallback] when possible, as [LocaleResolutionCallback] only
/// recieves a subset of the information provided in [LocaleListResolutionCallback].
51 52
///
/// A [LocaleResolutionCallback] is responsible for computing the locale of the app's
53
/// [Localizations] object when the app starts and when user changes the default
54
/// locale for the device after [LocaleListResolutionCallback] fails or is not provided.
55
///
56 57 58
/// This callback is also used if the app is created with a specific locale using
/// the [new WidgetsApp] `locale` parameter.
///
59 60 61 62 63
/// 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
/// locales. If [locale] is null, then Flutter has not yet recieved the locale
/// information from the platform. The [supportedLocales] parameter is just the value of
64
/// [WidgetsApp.supportedLocales].
65 66 67 68 69
///
/// See also:
///
///  * [LocaleListResolutionCallback], which takes a list of preferred locales (instead of one locale).
///    Resolutions by [LocaleListResolutionCallback] take precedence over [LocaleResolutionCallback].
70
typedef LocaleResolutionCallback = Locale Function(Locale locale, Iterable<Locale> supportedLocales);
71

72 73 74
/// The signature of [WidgetsApp.onGenerateTitle].
///
/// Used to generate a value for the app's [Title.title], which the device uses
75
/// to identify the app for the user. The `context` includes the [WidgetsApp]'s
76 77 78 79
/// [Localizations] widget so that this method can be used to produce a
/// localized title.
///
/// This function must not return null.
80
typedef GenerateAppTitle = String Function(BuildContext context);
81

82 83 84
/// The signature of [WidgetsApp.pageRouteBuilder].
///
/// Creates a [PageRoute] using the given [RouteSettings] and [WidgetBuilder].
85
typedef PageRouteFactory = PageRoute<T> Function<T>(RouteSettings settings, WidgetBuilder builder);
86

Ian Hickson's avatar
Ian Hickson committed
87 88 89
/// A convenience class that wraps a number of widgets that are commonly
/// required for an application.
///
90 91 92
/// One of the primary roles that [WidgetsApp] provides is binding the system
/// back button to popping the [Navigator] or quitting the application.
///
Ian Hickson's avatar
Ian Hickson committed
93
/// See also: [CheckedModeBanner], [DefaultTextStyle], [MediaQuery],
94
/// [Localizations], [Title], [Navigator], [Overlay], [SemanticsDebugger] (the
95
/// widgets wrapped by this one).
96
class WidgetsApp extends StatefulWidget {
97 98
  /// Creates a widget that wraps a number of widgets that are commonly
  /// required for an application.
99
  ///
100 101
  /// The boolean arguments, [color], and [navigatorObservers] must not be null.
  ///
102 103 104 105 106 107 108 109 110 111 112
  /// 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 `'/'`.
  ///
113 114 115 116 117 118 119 120 121 122 123
  /// 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
124 125 126 127 128 129 130 131 132 133 134
  /// [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.
135 136 137 138
  ///
  /// 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 :-(
139
    Key key,
140
    this.navigatorKey,
141
    this.onGenerateRoute,
142
    this.onUnknownRoute,
143
    this.navigatorObservers = const <NavigatorObserver>[],
144
    this.initialRoute,
145 146 147
    this.pageRouteBuilder,
    this.home,
    this.routes = const <String, WidgetBuilder>{},
148
    this.builder,
149
    this.title = '',
150
    this.onGenerateTitle,
151
    this.textStyle,
152
    @required this.color,
153 154
    this.locale,
    this.localizationsDelegates,
155
    this.localeListResolutionCallback,
156
    this.localeResolutionCallback,
157
    this.supportedLocales = const <Locale>[Locale('en', 'US')],
158 159 160 161 162 163
    this.showPerformanceOverlay = false,
    this.checkerboardRasterCacheImages = false,
    this.checkerboardOffscreenLayers = false,
    this.showSemanticsDebugger = false,
    this.debugShowWidgetInspector = false,
    this.debugShowCheckedModeBanner = true,
164
    this.inspectorSelectButtonBuilder,
165
  }) : assert(navigatorObservers != null),
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
       assert(routes != null),
       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).'
       ),
205 206 207 208 209 210 211 212
       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.'
       ),
213
       assert(title != null),
214
       assert(color != null),
215
       assert(supportedLocales != null && supportedLocales.isNotEmpty),
216 217
       assert(showPerformanceOverlay != null),
       assert(checkerboardRasterCacheImages != null),
218
       assert(checkerboardOffscreenLayers != null),
219
       assert(showSemanticsDebugger != null),
220
       assert(debugShowCheckedModeBanner != null),
221
       assert(debugShowWidgetInspector != null),
222
       super(key: key);
223

224
  /// {@template flutter.widgets.widgetsApp.navigatorKey}
225 226 227 228 229 230 231 232 233 234 235
  /// 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.
236
  ///
237 238
  /// The [Navigator] is only built if [onGenerateRoute] is not null; if it is
  /// null, [navigatorKey] must also be null.
239
  /// {@endtemplate}
240
  final GlobalKey<NavigatorState> navigatorKey;
241

xster's avatar
xster committed
242
  /// {@template flutter.widgets.widgetsApp.onGenerateRoute}
243
  /// The route generator callback used when the app is navigated to a
Ian Hickson's avatar
Ian Hickson committed
244
  /// named route.
245 246 247 248 249 250 251 252
  ///
  /// 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.
253 254 255 256 257 258
  ///
  /// 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
259
  /// {@endtemplate}
260
  ///
261 262 263
  /// 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.
264 265
  final RouteFactory onGenerateRoute;

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
  /// 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).
299
  /// {@endtemplate}
300 301 302 303 304 305 306 307 308 309 310 311 312
  ///
  /// 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.
313
  ///
314 315 316 317 318 319 320 321 322 323 324 325 326 327
  /// {@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.
328
  /// {@endtemplate}
329 330 331 332 333 334
  ///
  /// 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
335
  /// {@template flutter.widgets.widgetsApp.onUnknownRoute}
336 337 338
  /// Called when [onGenerateRoute] fails to generate a route, except for the
  /// [initialRoute].
  ///
339 340 341 342 343 344
  /// 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.
345
  ///
346 347 348 349
  /// 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}
350 351
  final RouteFactory onUnknownRoute;

xster's avatar
xster committed
352 353
  /// {@template flutter.widgets.widgetsApp.initialRoute}
  /// The name of the first route to show, if a [Navigator] is built.
354
  ///
355 356 357 358 359 360 361 362 363 364 365 366
  /// Defaults to [Window.defaultRouteName], which may be overridden by the code
  /// that launched the application.
  ///
  /// If the route contains slashes, 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.
  ///
  /// If any part of this process fails to generate routes, then the
  /// [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.
367 368 369
  /// 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.
370
  ///
371 372 373 374 375
  /// 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.
376
  /// {@endtemplate}
377 378
  final String initialRoute;

xster's avatar
xster committed
379
  /// {@template flutter.widgets.widgetsApp.navigatorObservers}
380 381 382 383
  /// 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.
384
  ///
385 386 387 388
  /// 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}
389 390
  final List<NavigatorObserver> navigatorObservers;

xster's avatar
xster committed
391
  /// {@template flutter.widgets.widgetsApp.builder}
392 393 394 395 396 397 398 399 400 401 402 403 404 405
  /// 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
406 407 408
  /// For specifically overriding the [title] with a value based on the
  /// [Localizations], consider [onGenerateTitle] instead.
  ///
409 410 411
  /// The [builder] callback is passed two arguments, the [BuildContext] (as
  /// `context`) and a [Navigator] widget (as `child`).
  ///
412 413 414
  /// 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.
415
  ///
416 417 418 419 420 421
  /// 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.
422 423
  ///
  /// If [builder] is null, it is as if a builder was specified that returned
424 425 426 427 428 429 430 431
  /// 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}
432 433
  final TransitionBuilder builder;

xster's avatar
xster committed
434
  /// {@template flutter.widgets.widgetsApp.title}
435 436 437
  /// 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
438 439 440
  /// 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.
441 442
  ///
  /// To provide a localized title instead, use [onGenerateTitle].
xster's avatar
xster committed
443
  /// {@endtemplate}
444 445
  final String title;

xster's avatar
xster committed
446
  /// {@template flutter.widgets.widgetsApp.onGenerateTitle}
447 448 449 450 451 452 453 454 455 456 457
  /// 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
458
  /// {@endtemplate}
459 460 461 462 463
  final GenerateAppTitle onGenerateTitle;

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

xster's avatar
xster committed
464
  /// {@template flutter.widgets.widgetsApp.color}
465 466 467 468 469
  /// 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
470
  /// {@endtemplate}
471 472
  final Color color;

xster's avatar
xster committed
473
  /// {@template flutter.widgets.widgetsApp.locale}
474 475 476 477
  /// 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.
478
  ///
479 480 481
  /// The value of [Localizations.locale] will equal this locale if
  /// it matches one of the [supportedLocales]. Otherwise it will be
  /// the first [supportedLocale].
xster's avatar
xster committed
482
  /// {@endtemplate}
483 484 485 486 487 488 489
  ///
  /// See also:
  ///
  ///  * [localeResolutionCallback], which can override the default
  ///    [supportedLocales] matching algorithm.
  ///  * [localizationsDelegates], which collectively define all of the localized
  ///    resources used by this app.
490 491
  final Locale locale;

xster's avatar
xster committed
492
  /// {@template flutter.widgets.widgetsApp.localizationsDelegates}
493 494 495 496
  /// 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
497
  /// {@endtemplate}
498
  final Iterable<LocalizationsDelegate<dynamic>> localizationsDelegates;
499

500
  /// {@template flutter.widgets.widgetsApp.localeListResolutionCallback}
501 502 503 504
  /// This callback is responsible for choosing the app's locale
  /// when the app is started, and when the user changes the
  /// device's locale.
  ///
505 506 507 508 509 510
  /// 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 [WidgetsApp.basicLocaleListResolution]
  /// fallback algorithm will be used.
511
  ///
512
  /// The priority of each available fallback is:
513
  ///
514 515 516
  ///  1. [localeListResolutionCallback] is attempted first.
  ///  2. [localeResolutionCallback] is attempted second.
  ///  3. Flutter's [WidgetsApp.basicLocaleListResolution] algorithm is attempted last.
517 518 519 520 521
  ///
  /// Properly localized projects should provide a more advanced algorithm than
  /// [basicLocaleListResolution] as it does not implement a complete algorithm
  /// (such as the one defined in [Unicode TR35](https://unicode.org/reports/tr35/#LanguageMatching))
  /// and is optimized for speed at the detriment of some uncommon edge-cases.
xster's avatar
xster committed
522
  /// {@endtemplate}
523
  ///
524 525 526 527 528
  /// This callback considers the entire list of preferred locales.
  ///
  /// This algorithm should be able to handle a null or empty list of preferred locales,
  /// which indicates Flutter has not yet recieved locale information from the platform.
  ///
529 530
  /// See also:
  ///
531
  ///  * [MaterialApp.localeListResolutionCallback], which sets the callback of the
532
  ///    [WidgetsApp] it creates.
533 534
  ///  * [basicLocaleListResolution], a static method that implements the locale resolution
  ///    algorithm that is used when no custom locale resolution algorithm is provided.
535 536 537 538 539 540 541 542 543 544 545 546 547
  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
  /// Flutter has not yet recieved locale information from the platform.
  ///
  /// See also:
  ///
548
  ///  * [MaterialApp.localeResolutionCallback], which sets the callback of the
549
  ///    [WidgetsApp] it creates.
550 551
  ///  * [basicLocaleListResolution], a static method that implements the locale resolution
  ///    algorithm that is used when no custom locale resolution algorithm is provided.
552 553
  final LocaleResolutionCallback localeResolutionCallback;

xster's avatar
xster committed
554
  /// {@template flutter.widgets.widgetsApp.supportedLocales}
555 556 557 558 559 560 561 562
  /// 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')]`.
  ///
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
  /// The order of the list matters. The default locale resolution algorithm,
  /// [basicLocaleListResolution], attempts to match by the following priority:
  ///
  ///  1. [Locale.languageCode], [Locale.scriptCode], and [Locale.countryCode]
  ///  2. [Locale.languageCode] and [Locale.countryCode] only
  ///  3. [Locale.languageCode] and [Locale.countryCode] only
  ///  4. [Locale.languageCode] only
  ///  6. [Locale.countryCode] only when all [preferredLocales] fail to match
  ///  5. returns [supportedLocales.first] as a fallback
  ///
  /// When more than one supported locale matches one of these criteria, only the first
  /// matching locale is returned. See [basicLocaleListResolution] for a complete
  /// description of the algorithm.
  ///
  /// 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.
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
  ///
  /// 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
  /// locale (eg. 'zh'), language+script only locales (eg. 'zh_Hans' and 'zh_Hant'),
  /// and any language+script+country locales (eg. 'zh_Hans_CN'). Fully defining all of
  /// 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
610
  /// {@endtemplate}
611 612 613 614 615 616 617
  ///
  /// 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.
618
  ///  * [localizationsDelegates], which collectively define all of the localized
619
  ///    resources used by this app.
620 621
  ///  * [basicLocaleListResolution], a static method that implements the locale resolution
  ///    algorithm that is used when no custom locale resolution algorithm is provided.
622 623
  final Iterable<Locale> supportedLocales;

624
  /// Turns on a performance overlay.
xster's avatar
xster committed
625 626 627 628
  ///
  /// See also:
  ///
  ///  * <https://flutter.io/debugging/#performanceoverlay>
629 630
  final bool showPerformanceOverlay;

631
  /// Checkerboards raster cache images.
632 633
  ///
  /// See [PerformanceOverlay.checkerboardRasterCacheImages].
634 635
  final bool checkerboardRasterCacheImages;

636 637 638 639 640
  /// Checkerboards layers rendered to offscreen bitmaps.
  ///
  /// See [PerformanceOverlay.checkerboardOffscreenLayers].
  final bool checkerboardOffscreenLayers;

641 642 643 644
  /// Turns on an overlay that shows the accessibility information
  /// reported by the framework.
  final bool showSemanticsDebugger;

645 646 647 648 649 650 651 652 653 654 655
  /// 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
656
  /// select mode without requiring [WidgetInspector] to depend on the
657 658 659
  /// material package.
  final InspectorSelectButtonBuilder inspectorSelectButtonBuilder;

xster's avatar
xster committed
660 661
  /// {@template flutter.widgets.widgetsApp.debugShowCheckedModeBanner}
  /// Turns on a little "DEBUG" banner in checked mode to indicate
662 663 664 665 666 667 668
  /// 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
669
  /// This banner is intended to deter people from complaining that your
670 671 672 673
  /// 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
674
  /// {@endtemplate}
675 676
  final bool debugShowCheckedModeBanner;

677 678
  /// If true, forces the performance overlay to be visible in all instances.
  ///
679
  /// Used by the `showPerformanceOverlay` observatory extension.
680 681
  static bool showPerformanceOverlayOverride = false;

682 683 684 685 686 687 688 689 690 691
  /// 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;

692 693
  /// If false, prevents the debug banner from being visible.
  ///
694
  /// Used by the `debugAllowBanner` observatory extension.
695 696 697 698 699
  ///
  /// This is how `flutter run` turns off the banner when you take a screen shot
  /// with "s".
  static bool debugAllowBannerOverride = true;

700
  @override
701
  _WidgetsAppState createState() => _WidgetsAppState();
702 703
}

704
class _WidgetsAppState extends State<WidgetsApp> implements WidgetsBindingObserver {
705

706
  // STATE LIFECYCLE
707

708
  @override
709 710
  void initState() {
    super.initState();
711
    _updateNavigator();
712
    _locale = _resolveLocales(WidgetsBinding.instance.window.locales, widget.supportedLocales);
713
    WidgetsBinding.instance.addObserver(this);
714 715
  }

716 717 718 719 720 721 722
  @override
  void didUpdateWidget(WidgetsApp oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.navigatorKey != oldWidget.navigatorKey)
      _updateNavigator();
  }

723
  @override
724
  void dispose() {
725
    WidgetsBinding.instance.removeObserver(this);
726 727 728
    super.dispose();
  }

729
  @override
730
  void didChangeAppLifecycleState(AppLifecycleState state) { }
731 732 733 734 735 736 737 738 739 740

  @override
  void didHaveMemoryPressure() { }


  // NAVIGATOR

  GlobalKey<NavigatorState> _navigator;

  void _updateNavigator() {
741 742 743 744 745
    _navigator = widget.navigatorKey ?? GlobalObjectKey<NavigatorState>(this);
  }

  Route<dynamic> _onGenerateRoute(RouteSettings settings) {
    final String name = settings.name;
746 747 748 749 750
    final WidgetBuilder pageContentBuilder = name == Navigator.defaultRouteName && widget.home != null
        ? (BuildContext context) => widget.home
        : widget.routes[name];

    if (pageContentBuilder != null) {
751 752 753
      assert(widget.pageRouteBuilder != null,
        'The default onGenerateRoute handler for WidgetsApp must have a '
        'pageRouteBuilder set if the home or routes properties are set.');
754
      final Route<dynamic> route = widget.pageRouteBuilder<dynamic>(
755
        settings,
756
        pageContentBuilder,
757 758 759 760
      );
      assert(route != null,
        'The pageRouteBuilder for WidgetsApp must return a valid non-null Route.');
      return route;
761
    }
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
    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) {
        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.'
        );
      }
      return true;
    }());
    return result;
797 798
  }

799
  // On Android: the user has pressed the back button.
800
  @override
801
  Future<bool> didPopRoute() async {
802
    assert(mounted);
803 804 805
    final NavigatorState navigator = _navigator?.currentState;
    if (navigator == null)
      return false;
806
    return await navigator.maybePop();
807 808
  }

809 810 811
  @override
  Future<bool> didPushRoute(String route) async {
    assert(mounted);
812 813 814
    final NavigatorState navigator = _navigator?.currentState;
    if (navigator == null)
      return false;
815 816 817 818
    navigator.pushNamed(route);
    return true;
  }

819

820 821
  // LOCALIZATION

822
  /// This is the resolved locale, and is one of the supportedLocales.
823 824
  Locale _locale;

825 826 827 828 829 830 831 832
  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.
833
    if (widget.localeResolutionCallback != null) {
834 835 836 837
      final Locale locale = widget.localeResolutionCallback(
        preferredLocales != null && preferredLocales.isNotEmpty ? preferredLocales.first : null,
        widget.supportedLocales,
      );
838 839 840
      if (locale != null)
        return locale;
    }
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
    // Both callbacks failed, falling back to default algorithm.
    return basicLocaleListResolution(preferredLocales, supportedLocales);
  }

  /// The default locale resolution algorithm.
  ///
  /// Custom resolution algorithms can be provided through [WidgetsApp.localeListResolutionCallback]
  /// or [WidgetsApp.localeResolutionCallback].
  ///
  /// When no custom locale resolition 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 locale in [preferredLocales] 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 locale in preferredLocales with a
  /// perfect match can supercede 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 [preferredLocales] 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.
  ///
873 874 875 876 877 878 879 880 881
  /// To summarize, the main matching priority is:
  ///
  ///  1. [Locale.languageCode], [Locale.scriptCode], and [Locale.countryCode]
  ///  2. [Locale.languageCode] and [Locale.countryCode] only
  ///  3. [Locale.languageCode] and [Locale.countryCode] only
  ///  4. [Locale.languageCode] only (with caveats, see above)
  ///  6. [Locale.countryCode] only when all [preferredLocales] fail to match
  ///  5. returns [supportedLocales.first] as a fallback
  ///
882 883 884 885 886 887 888 889 890
  /// 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) {
891 892
      return supportedLocales.first;
    }
893 894 895 896 897 898 899 900 901 902 903 904 905 906
    // 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 (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;
    }
907

908 909 910 911 912
    // 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.
913
    Locale matchesLanguageCode;
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
    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) {
931
        final Locale match = languageAndCountryLocales['${userLocale.languageCode}_${userLocale.countryCode}'];
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
        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 familar with a
      // language from their listed country.
      if (matchesCountryCode == null && userLocale.countryCode != null) {
        match = countryLocales[userLocale.countryCode];
        if (match != null) {
          matchesCountryCode = match;
        }
      }
964
    }
965 966 967 968 969
    // 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
    // suported locale.
    final Locale resolvedLocale = matchesLanguageCode ?? matchesCountryCode ?? supportedLocales.first;
    return resolvedLocale;
970 971
  }

972
  @override
973 974
  void didChangeLocales(List<Locale> locales) {
    final Locale newLocale = _resolveLocales(locales, widget.supportedLocales);
975
    if (newLocale != _locale) {
976
      setState(() {
977
        _locale = newLocale;
978 979 980 981
      });
    }
  }

982
  // Combine the Localizations for Widgets with the ones contributed
983 984 985
  // 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
986
  // WidgetsLocalizations.delegate.
987 988 989
  Iterable<LocalizationsDelegate<dynamic>> get _localizationsDelegates sync* {
    if (widget.localizationsDelegates != null)
      yield* widget.localizationsDelegates;
990
    yield DefaultWidgetsLocalizations.delegate;
991 992
  }

993 994 995 996 997
  // ACCESSIBILITY

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

1003 1004 1005

  // METRICS

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

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

1023 1024 1025 1026 1027 1028 1029 1030 1031
  // 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.
    });
  }
1032 1033

  // BUILDER
1034

1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
  bool _debugCheckLocalizations(Locale appLocale) {
    assert(() {
      final Set<Type> unsupportedTypes =
        _localizationsDelegates.map<Type>((LocalizationsDelegate<dynamic> delegate) => delegate.type).toSet();
      for (LocalizationsDelegate<dynamic> delegate in _localizationsDelegates) {
        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(
        'Warning: This application\'s locale, $appLocale, is not supported by all of its\n'
        'localization delegates.'
      );
      for (Type unsupportedType in unsupportedTypes) {
        // 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(
        'See https://flutter.io/tutorials/internationalization/ for more\n'
        'information about configuring an app\'s locale, supportedLocales,\n'
        'and localizationsDelegates parameters.'
      );
      message.writeln('\u2550' * 8);
      debugPrint(message.toString());
      return true;
    }());
    return true;
  }

1082
  @override
1083
  Widget build(BuildContext context) {
1084 1085
    Widget navigator;
    if (_navigator != null) {
1086
      navigator = Navigator(
1087
        key: _navigator,
1088
        // If window.defaultRouteName isn't '/', we should assume it was set
1089 1090
        // intentionally via `setInitialRoute`, and should override whatever
        // is in [widget.initialRoute].
1091 1092 1093
        initialRoute: WidgetsBinding.instance.window.defaultRouteName != Navigator.defaultRouteName
            ? WidgetsBinding.instance.window.defaultRouteName
            : widget.initialRoute ?? WidgetsBinding.instance.window.defaultRouteName,
1094 1095
        onGenerateRoute: _onGenerateRoute,
        onUnknownRoute: _onUnknownRoute,
1096 1097 1098 1099 1100 1101
        observers: widget.navigatorObservers,
      );
    }

    Widget result;
    if (widget.builder != null) {
1102
      result = Builder(
1103 1104 1105 1106 1107 1108 1109 1110
        builder: (BuildContext context) {
          return widget.builder(context, navigator);
        },
      );
    } else {
      assert(navigator != null);
      result = navigator;
    }
1111

1112
    if (widget.textStyle != null) {
1113
      result = DefaultTextStyle(
1114
        style: widget.textStyle,
1115
        child: result,
Ian Hickson's avatar
Ian Hickson committed
1116 1117
      );
    }
1118 1119 1120 1121

    PerformanceOverlay performanceOverlay;
    // We need to push a performance overlay if any of the display or checkerboarding
    // options are set.
1122
    if (widget.showPerformanceOverlay || WidgetsApp.showPerformanceOverlayOverride) {
1123
      performanceOverlay = PerformanceOverlay.allEnabled(
1124 1125
        checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages,
        checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers,
1126 1127
      );
    } else if (widget.checkerboardRasterCacheImages || widget.checkerboardOffscreenLayers) {
1128
      performanceOverlay = PerformanceOverlay(
1129 1130
        checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages,
        checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers,
1131
      );
1132 1133
    }
    if (performanceOverlay != null) {
1134
      result = Stack(
1135 1136
        children: <Widget>[
          result,
1137
          Positioned(top: 0.0, left: 0.0, right: 0.0, child: performanceOverlay),
1138 1139 1140
        ]
      );
    }
1141

1142
    if (widget.showSemanticsDebugger) {
1143
      result = SemanticsDebugger(
1144
        child: result,
1145 1146
      );
    }
1147

1148
    assert(() {
1149
      if (widget.debugShowWidgetInspector || WidgetsApp.debugShowWidgetInspectorOverride) {
1150
        result = WidgetInspector(
1151 1152 1153 1154
          child: result,
          selectButtonBuilder: widget.inspectorSelectButtonBuilder,
        );
      }
1155
      if (widget.debugShowCheckedModeBanner && WidgetsApp.debugAllowBannerOverride) {
1156
        result = CheckedModeBanner(
1157
          child: result,
1158 1159 1160
        );
      }
      return true;
1161
    }());
1162

1163 1164
    Widget title;
    if (widget.onGenerateTitle != null) {
1165
      title = Builder(
1166
        // This Builder exists to provide a context below the Localizations widget.
1167
        // The onGenerateTitle callback can refer to Localizations via its context
1168 1169 1170 1171
        // parameter.
        builder: (BuildContext context) {
          final String title = widget.onGenerateTitle(context);
          assert(title != null, 'onGenerateTitle must return a non-null String');
1172
          return Title(
1173 1174 1175 1176 1177 1178 1179
            title: title,
            color: widget.color,
            child: result,
          );
        },
      );
    } else {
1180
      title = Title(
1181 1182 1183 1184 1185 1186
        title: widget.title,
        color: widget.color,
        child: result,
      );
    }

1187
    final Locale appLocale = widget.locale != null
1188
      ? _resolveLocales(<Locale>[widget.locale], widget.supportedLocales)
1189 1190 1191 1192
      : _locale;

    assert(_debugCheckLocalizations(appLocale));

1193
    return MediaQuery(
1194
      data: MediaQueryData.fromWindow(WidgetsBinding.instance.window),
1195
      child: Localizations(
1196
        locale: appLocale,
1197
        delegates: _localizationsDelegates.toList(),
1198
        child: title,
1199 1200
      ),
    );
1201 1202
  }
}