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

import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';

import 'button.dart';
import 'colors.dart';
import 'icons.dart';
11
import 'interface_level.dart';
12
import 'localizations.dart';
13
import 'route.dart';
xster's avatar
xster committed
14
import 'theme.dart';
xster's avatar
xster committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

/// An application that uses Cupertino design.
///
/// A convenience widget that wraps a number of widgets that are commonly
/// required for an iOS-design targeting application. It builds upon a
/// [WidgetsApp] by iOS specific defaulting such as fonts and scrolling
/// physics.
///
/// The [CupertinoApp] configures the top-level [Navigator] to search for routes
/// in the following order:
///
///  1. For the `/` route, the [home] property, if non-null, is used.
///
///  2. Otherwise, the [routes] table is used, if it has an entry for the route.
///
///  3. Otherwise, [onGenerateRoute] is called, if provided. It should return a
///     non-null value for any _valid_ route not handled by [home] and [routes].
///
///  4. Finally if all else fails [onUnknownRoute] is called.
///
/// If [home], [routes], [onGenerateRoute], and [onUnknownRoute] are all null,
/// and [builder] is not null, then no [Navigator] is created.
///
38 39 40
/// This widget also configures the observer of the top-level [Navigator] (if
/// any) to perform [Hero] animations.
///
Sigurd Meldgaard's avatar
Sigurd Meldgaard committed
41
/// Use this widget with caution on Android since it may produce behaviors
xster's avatar
xster committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
/// Android users are not expecting such as:
///
///  * Pages will be dismissible via a back swipe.
///  * Scrolling past extremities will trigger iOS-style spring overscrolls.
///  * The San Francisco font family is unavailable on Android and can result
///    in undefined font behavior.
///
/// See also:
///
///  * [CupertinoPageScaffold], which provides a standard page layout default
///    with nav bars.
///  * [Navigator], which is used to manage the app's stack of pages.
///  * [CupertinoPageRoute], which defines an app page that transitions in an
///    iOS-specific way.
///  * [WidgetsApp], which defines the basic app elements but does not depend
///    on the Cupertino library.
class CupertinoApp extends StatefulWidget {
  /// Creates a CupertinoApp.
  ///
  /// At least one of [home], [routes], [onGenerateRoute], or [builder] must be
  /// non-null. If only [routes] is given, it must include an entry for the
  /// [Navigator.defaultRouteName] (`/`), since that is the route used when the
  /// application is launched with an intent that specifies an otherwise
  /// unsupported route.
  ///
  /// This class creates an instance of [WidgetsApp].
  ///
  /// The boolean arguments, [routes], and [navigatorObservers], must not be null.
70
  const CupertinoApp({
71
    Key? key,
72
    this.navigatorKey,
xster's avatar
xster committed
73
    this.home,
xster's avatar
xster committed
74
    this.theme,
75
    Map<String, Widget Function(BuildContext)> this.routes = const <String, WidgetBuilder>{},
xster's avatar
xster committed
76 77
    this.initialRoute,
    this.onGenerateRoute,
78
    this.onGenerateInitialRoutes,
xster's avatar
xster committed
79
    this.onUnknownRoute,
80
    List<NavigatorObserver> this.navigatorObservers = const <NavigatorObserver>[],
xster's avatar
xster committed
81 82 83 84 85 86
    this.builder,
    this.title = '',
    this.onGenerateTitle,
    this.color,
    this.locale,
    this.localizationsDelegates,
87
    this.localeListResolutionCallback,
xster's avatar
xster committed
88
    this.localeResolutionCallback,
89
    this.supportedLocales = const <Locale>[Locale('en', 'US')],
xster's avatar
xster committed
90 91 92 93 94
    this.showPerformanceOverlay = false,
    this.checkerboardRasterCacheImages = false,
    this.checkerboardOffscreenLayers = false,
    this.showSemanticsDebugger = false,
    this.debugShowCheckedModeBanner = true,
95 96
    this.shortcuts,
    this.actions,
97
    this.restorationScopeId,
xster's avatar
xster committed
98 99 100 101 102 103 104 105
  }) : assert(routes != null),
       assert(navigatorObservers != null),
       assert(title != null),
       assert(showPerformanceOverlay != null),
       assert(checkerboardRasterCacheImages != null),
       assert(checkerboardOffscreenLayers != null),
       assert(showSemanticsDebugger != null),
       assert(debugShowCheckedModeBanner != null),
106 107 108 109 110 111 112 113
       routeInformationProvider = null,
       routeInformationParser = null,
       routerDelegate = null,
       backButtonDispatcher = null,
       super(key: key);

  /// Creates a [CupertinoApp] that uses the [Router] instead of a [Navigator].
  const CupertinoApp.router({
114
    Key? key,
115
    this.routeInformationProvider,
116 117
    required RouteInformationParser<Object> this.routeInformationParser,
    required RouterDelegate<Object> this.routerDelegate,
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
    this.backButtonDispatcher,
    this.theme,
    this.builder,
    this.title = '',
    this.onGenerateTitle,
    this.color,
    this.locale,
    this.localizationsDelegates,
    this.localeListResolutionCallback,
    this.localeResolutionCallback,
    this.supportedLocales = const <Locale>[Locale('en', 'US')],
    this.showPerformanceOverlay = false,
    this.checkerboardRasterCacheImages = false,
    this.checkerboardOffscreenLayers = false,
    this.showSemanticsDebugger = false,
    this.debugShowCheckedModeBanner = true,
    this.shortcuts,
    this.actions,
136
    this.restorationScopeId,
137 138 139 140 141 142 143 144 145 146 147 148 149 150
  }) : assert(title != null),
       assert(showPerformanceOverlay != null),
       assert(checkerboardRasterCacheImages != null),
       assert(checkerboardOffscreenLayers != null),
       assert(showSemanticsDebugger != null),
       assert(debugShowCheckedModeBanner != null),
       navigatorObservers = null,
       navigatorKey = null,
       onGenerateRoute = null,
       home = null,
       onGenerateInitialRoutes = null,
       onUnknownRoute = null,
       routes = null,
       initialRoute = null,
xster's avatar
xster committed
151 152
       super(key: key);

153
  /// {@macro flutter.widgets.widgetsApp.navigatorKey}
154
  final GlobalKey<NavigatorState>? navigatorKey;
155 156

  /// {@macro flutter.widgets.widgetsApp.home}
157
  final Widget? home;
xster's avatar
xster committed
158

xster's avatar
xster committed
159 160 161 162
  /// The top-level [CupertinoTheme] styling.
  ///
  /// A null [theme] or unspecified [theme] attributes will default to iOS
  /// system values.
163
  final CupertinoThemeData? theme;
xster's avatar
xster committed
164

xster's avatar
xster committed
165 166 167 168 169
  /// 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 [CupertinoPageRoute] that performs
170
  /// an appropriate transition, including [Hero] animations, to the new route.
xster's avatar
xster committed
171
  ///
172
  /// {@macro flutter.widgets.widgetsApp.routes}
173
  final Map<String, WidgetBuilder>? routes;
xster's avatar
xster committed
174 175

  /// {@macro flutter.widgets.widgetsApp.initialRoute}
176
  final String? initialRoute;
xster's avatar
xster committed
177 178

  /// {@macro flutter.widgets.widgetsApp.onGenerateRoute}
179
  final RouteFactory? onGenerateRoute;
xster's avatar
xster committed
180

181
  /// {@macro flutter.widgets.widgetsApp.onGenerateInitialRoutes}
182
  final InitialRouteListFactory? onGenerateInitialRoutes;
183

xster's avatar
xster committed
184
  /// {@macro flutter.widgets.widgetsApp.onUnknownRoute}
185
  final RouteFactory? onUnknownRoute;
xster's avatar
xster committed
186 187

  /// {@macro flutter.widgets.widgetsApp.navigatorObservers}
188
  final List<NavigatorObserver>? navigatorObservers;
xster's avatar
xster committed
189

190
  /// {@macro flutter.widgets.widgetsApp.routeInformationProvider}
191
  final RouteInformationProvider? routeInformationProvider;
192 193

  /// {@macro flutter.widgets.widgetsApp.routeInformationParser}
194
  final RouteInformationParser<Object>? routeInformationParser;
195 196

  /// {@macro flutter.widgets.widgetsApp.routerDelegate}
197
  final RouterDelegate<Object>? routerDelegate;
198 199

  /// {@macro flutter.widgets.widgetsApp.backButtonDispatcher}
200
  final BackButtonDispatcher? backButtonDispatcher;
201

xster's avatar
xster committed
202
  /// {@macro flutter.widgets.widgetsApp.builder}
203
  final TransitionBuilder? builder;
xster's avatar
xster committed
204 205 206 207 208 209 210 211 212

  /// {@macro flutter.widgets.widgetsApp.title}
  ///
  /// This value is passed unmodified to [WidgetsApp.title].
  final String title;

  /// {@macro flutter.widgets.widgetsApp.onGenerateTitle}
  ///
  /// This value is passed unmodified to [WidgetsApp.onGenerateTitle].
213
  final GenerateAppTitle? onGenerateTitle;
xster's avatar
xster committed
214 215

  /// {@macro flutter.widgets.widgetsApp.color}
216
  final Color? color;
xster's avatar
xster committed
217 218

  /// {@macro flutter.widgets.widgetsApp.locale}
219
  final Locale? locale;
xster's avatar
xster committed
220 221

  /// {@macro flutter.widgets.widgetsApp.localizationsDelegates}
222
  final Iterable<LocalizationsDelegate<dynamic>>? localizationsDelegates;
xster's avatar
xster committed
223

224 225 226
  /// {@macro flutter.widgets.widgetsApp.localeListResolutionCallback}
  ///
  /// This callback is passed along to the [WidgetsApp] built by this widget.
227
  final LocaleListResolutionCallback? localeListResolutionCallback;
228

xster's avatar
xster committed
229 230 231
  /// {@macro flutter.widgets.widgetsApp.localeResolutionCallback}
  ///
  /// This callback is passed along to the [WidgetsApp] built by this widget.
232
  final LocaleResolutionCallback? localeResolutionCallback;
xster's avatar
xster committed
233 234 235 236 237 238 239 240 241 242

  /// {@macro flutter.widgets.widgetsApp.supportedLocales}
  ///
  /// It is passed along unmodified to the [WidgetsApp] built by this widget.
  final Iterable<Locale> supportedLocales;

  /// Turns on a performance overlay.
  ///
  /// See also:
  ///
243
  ///  * <https://flutter.dev/debugging/#performanceoverlay>
xster's avatar
xster committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
  final bool showPerformanceOverlay;

  /// Turns on checkerboarding of raster cache images.
  final bool checkerboardRasterCacheImages;

  /// Turns on checkerboarding of layers rendered to offscreen bitmaps.
  final bool checkerboardOffscreenLayers;

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

  /// {@macro flutter.widgets.widgetsApp.debugShowCheckedModeBanner}
  final bool debugShowCheckedModeBanner;

259
  /// {@macro flutter.widgets.widgetsApp.shortcuts}
260
  /// {@tool snippet}
261 262 263 264 265 266 267 268 269 270 271 272 273
  /// 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,
274
  ///       LogicalKeySet(LogicalKeyboardKey.select): const ActivateIntent(),
275 276 277 278 279 280 281 282 283 284
  ///     },
  ///     color: const Color(0xFFFF0000),
  ///     builder: (BuildContext context, Widget child) {
  ///       return const Placeholder();
  ///     },
  ///   );
  /// }
  /// ```
  /// {@end-tool}
  /// {@macro flutter.widgets.widgetsApp.shortcuts.seeAlso}
285
  final Map<LogicalKeySet, Intent>? shortcuts;
286 287

  /// {@macro flutter.widgets.widgetsApp.actions}
288
  /// {@tool snippet}
289 290 291 292 293 294 295 296 297 298 299
  /// 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(
300
  ///     actions: <Type, Action<Intent>>{
301
  ///       ... WidgetsApp.defaultActions,
302 303
  ///       ActivateAction: CallbackAction(
  ///         onInvoke: (Intent intent) {
304
  ///           // Do something here...
305
  ///           return null;
306 307 308 309 310 311 312 313 314 315 316 317
  ///         },
  ///       ),
  ///     },
  ///     color: const Color(0xFFFF0000),
  ///     builder: (BuildContext context, Widget child) {
  ///       return const Placeholder();
  ///     },
  ///   );
  /// }
  /// ```
  /// {@end-tool}
  /// {@macro flutter.widgets.widgetsApp.actions.seeAlso}
318
  final Map<Type, Action<Intent>>? actions;
319

320 321 322
  /// {@macro flutter.widgets.widgetsApp.restorationScopeId}
  final String? restorationScopeId;

xster's avatar
xster committed
323
  @override
324
  _CupertinoAppState createState() => _CupertinoAppState();
325 326 327 328 329 330

  /// The [HeroController] used for Cupertino page transitions.
  ///
  /// Used by [CupertinoTabView] and [CupertinoApp].
  static HeroController createCupertinoHeroController() =>
      HeroController(); // Linear tweening.
xster's avatar
xster committed
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
}

class _AlwaysCupertinoScrollBehavior extends ScrollBehavior {
  @override
  Widget buildViewportChrome(BuildContext context, Widget child, AxisDirection axisDirection) {
    // Never build any overscroll glow indicators.
    return child;
  }

  @override
  ScrollPhysics getScrollPhysics(BuildContext context) {
    return const BouncingScrollPhysics();
  }
}

class _CupertinoAppState extends State<CupertinoApp> {
347
  late HeroController _heroController;
348
  bool get _usesRouter => widget.routerDelegate != null;
349

xster's avatar
xster committed
350 351 352
  @override
  void initState() {
    super.initState();
353
    _heroController = CupertinoApp.createCupertinoHeroController();
xster's avatar
xster committed
354 355
  }

356 357 358 359 360 361 362
  // Combine the default localization for Cupertino with the ones contributed
  // 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
  // _CupertinoLocalizationsDelegate.
  Iterable<LocalizationsDelegate<dynamic>> get _localizationsDelegates sync* {
    if (widget.localizationsDelegates != null)
363
      yield* widget.localizationsDelegates!;
364 365 366
    yield DefaultCupertinoLocalizations.delegate;
  }

367 368 369 370 371 372 373 374 375 376 377 378 379 380
  Widget _inspectorSelectButtonBuilder(BuildContext context, VoidCallback onPressed) {
    return CupertinoButton.filled(
      child: const Icon(
        CupertinoIcons.search,
        size: 28.0,
        color: CupertinoColors.white,
      ),
      padding: EdgeInsets.zero,
      onPressed: onPressed,
    );
  }

  WidgetsApp _buildWidgetApp(BuildContext context) {
    final CupertinoThemeData effectiveThemeData = CupertinoTheme.of(context);
381
    final Color color = CupertinoDynamicColor.resolve(widget.color ?? effectiveThemeData.primaryColor, context)!;
382 383 384 385 386

    if (_usesRouter) {
      return WidgetsApp.router(
        key: GlobalObjectKey(this),
        routeInformationProvider: widget.routeInformationProvider,
387 388
        routeInformationParser: widget.routeInformationParser!,
        routerDelegate: widget.routerDelegate!,
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
        backButtonDispatcher: widget.backButtonDispatcher,
        builder: widget.builder,
        title: widget.title,
        onGenerateTitle: widget.onGenerateTitle,
        textStyle: effectiveThemeData.textTheme.textStyle,
        color: color,
        locale: widget.locale,
        localizationsDelegates: _localizationsDelegates,
        localeResolutionCallback: widget.localeResolutionCallback,
        localeListResolutionCallback: widget.localeListResolutionCallback,
        supportedLocales: widget.supportedLocales,
        showPerformanceOverlay: widget.showPerformanceOverlay,
        checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages,
        checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers,
        showSemanticsDebugger: widget.showSemanticsDebugger,
        debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner,
        inspectorSelectButtonBuilder: _inspectorSelectButtonBuilder,
        shortcuts: widget.shortcuts,
        actions: widget.actions,
408
        restorationScopeId: widget.restorationScopeId,
409 410 411 412 413
      );
    }
    return WidgetsApp(
      key: GlobalObjectKey(this),
      navigatorKey: widget.navigatorKey,
414
      navigatorObservers: widget.navigatorObservers!,
415 416 417 418
      pageRouteBuilder: <T>(RouteSettings settings, WidgetBuilder builder) {
        return CupertinoPageRoute<T>(settings: settings, builder: builder);
      },
      home: widget.home,
419
      routes: widget.routes!,
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
      initialRoute: widget.initialRoute,
      onGenerateRoute: widget.onGenerateRoute,
      onGenerateInitialRoutes: widget.onGenerateInitialRoutes,
      onUnknownRoute: widget.onUnknownRoute,
      builder: widget.builder,
      title: widget.title,
      onGenerateTitle: widget.onGenerateTitle,
      textStyle: effectiveThemeData.textTheme.textStyle,
      color: color,
      locale: widget.locale,
      localizationsDelegates: _localizationsDelegates,
      localeResolutionCallback: widget.localeResolutionCallback,
      localeListResolutionCallback: widget.localeListResolutionCallback,
      supportedLocales: widget.supportedLocales,
      showPerformanceOverlay: widget.showPerformanceOverlay,
      checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages,
      checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers,
      showSemanticsDebugger: widget.showSemanticsDebugger,
      debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner,
      inspectorSelectButtonBuilder: _inspectorSelectButtonBuilder,
      shortcuts: widget.shortcuts,
      actions: widget.actions,
442
      restorationScopeId: widget.restorationScopeId,
443 444 445
    );
  }

xster's avatar
xster committed
446 447
  @override
  Widget build(BuildContext context) {
xster's avatar
xster committed
448 449
    final CupertinoThemeData effectiveThemeData = widget.theme ?? const CupertinoThemeData();

450 451
    return ScrollConfiguration(
      behavior: _AlwaysCupertinoScrollBehavior(),
452 453 454 455
      child: CupertinoUserInterfaceLevel(
        data: CupertinoUserInterfaceLevelData.base,
        child: CupertinoTheme(
          data: effectiveThemeData,
456 457 458 459 460
          child: HeroControllerScope(
            controller: _heroController,
            child: Builder(
              builder: _buildWidgetApp,
            ),
461
          ),
xster's avatar
xster committed
462
        ),
xster's avatar
xster committed
463 464 465 466
      ),
    );
  }
}