scaffold.dart 132 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.

Hixie's avatar
Hixie committed
5 6
import 'dart:async';
import 'dart:collection';
7
import 'dart:math' as math;
8
import 'dart:ui' show lerpDouble;
9

10
import 'package:flutter/foundation.dart';
11
import 'package:flutter/gestures.dart' show DragStartBehavior;
12
import 'package:flutter/widgets.dart';
13

14
import 'app_bar.dart';
15
import 'bottom_sheet.dart';
16
import 'colors.dart';
17
import 'curves.dart';
18
import 'debug.dart';
19
import 'divider.dart';
20
import 'drawer.dart';
21
import 'flexible_space_bar.dart';
22
import 'floating_action_button.dart';
23
import 'floating_action_button_location.dart';
24
import 'material.dart';
Hixie's avatar
Hixie committed
25
import 'snack_bar.dart';
26
import 'snack_bar_theme.dart';
27
import 'theme.dart';
28

29
// Examples can assume:
30
// late TabController tabController;
31
// void setState(VoidCallback fn) { }
32 33 34
// late String appBarTitle;
// late int tabCount;
// late TickerProvider tickerProvider;
35

36 37
const FloatingActionButtonLocation _kDefaultFloatingActionButtonLocation = FloatingActionButtonLocation.endFloat;
const FloatingActionButtonAnimator _kDefaultFloatingActionButtonAnimator = FloatingActionButtonAnimator.scaling;
38

39
const Curve _standardBottomSheetCurve = standardEasing;
40 41 42 43 44 45
// When the top of the BottomSheet crosses this threshold, it will start to
// shrink the FAB and show a scrim.
const double _kBottomSheetDominatesPercentage = 0.3;
const double _kMinBottomSheetScrimOpacity = 0.1;
const double _kMaxBottomSheetScrimOpacity = 0.6;

46
enum _ScaffoldSlot {
47
  body,
48
  appBar,
49
  bodyScrim,
50 51
  bottomSheet,
  snackBar,
52
  persistentFooter,
53
  bottomNavigationBar,
54 55
  floatingActionButton,
  drawer,
56
  endDrawer,
57
  statusBar,
58
}
Hans Muller's avatar
Hans Muller committed
59

60 61 62 63 64 65 66 67
/// Manages [SnackBar]s for descendant [Scaffold]s.
///
/// This class provides APIs for showing snack bars.
///
/// To display a snack bar, obtain the [ScaffoldMessengerState] for the current
/// [BuildContext] via [ScaffoldMessenger.of] and use the
/// [ScaffoldMessengerState.showSnackBar] function.
///
68 69 70 71 72 73
/// When the [ScaffoldMessenger] has nested [Scaffold] descendants, the
/// ScaffoldMessenger will only present a [SnackBar] to the root Scaffold of
/// the subtree of Scaffolds. In order to show SnackBars in the inner, nested
/// Scaffolds, set a new scope for your SnackBars by instantiating a new
/// ScaffoldMessenger in between the levels of nesting.
///
74
/// {@tool dartpad --template=stateless_widget_scaffold_center}
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
///
/// Here is an example of showing a [SnackBar] when the user presses a button.
///
/// ```dart
///   Widget build(BuildContext context) {
///     return OutlinedButton(
///       onPressed: () {
///         ScaffoldMessenger.of(context).showSnackBar(
///           const SnackBar(
///             content: Text('A SnackBar has been shown.'),
///           ),
///         );
///       },
///       child: const Text('Show SnackBar'),
///     );
///   }
/// ```
/// {@end-tool}
///
/// See also:
///
///  * [SnackBar], which is a temporary notification typically shown near the
///    bottom of the app using the [ScaffoldMessengerState.showSnackBar] method.
///  * [debugCheckHasScaffoldMessenger], which asserts that the given context
///    has a [ScaffoldMessenger] ancestor.
///  * Cookbook: [Display a SnackBar](https://flutter.dev/docs/cookbook/design/snackbars)
class ScaffoldMessenger extends StatefulWidget {
  /// Creates a widget that manages [SnackBar]s for [Scaffold] descendants.
  const ScaffoldMessenger({
    Key? key,
    required this.child,
  }) : assert(child != null),
       super(key: key);

  /// The widget below this widget in the tree.
  ///
111
  /// {@macro flutter.widgets.ProxyWidget.child}
112 113 114 115 116
  final Widget child;

  /// The state from the closest instance of this class that encloses the given
  /// context.
  ///
117
  /// {@tool dartpad --template=stateless_widget_scaffold_center}
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
  /// Typical usage of the [ScaffoldMessenger.of] function is to call it in
  /// response to a user gesture or an application state change.
  ///
  /// ```dart
  /// Widget build(BuildContext context) {
  ///   return ElevatedButton(
  ///     child: const Text('SHOW A SNACKBAR'),
  ///     onPressed: () {
  ///       ScaffoldMessenger.of(context).showSnackBar(
  ///         const SnackBar(
  ///           content: Text('Have a snack!'),
  ///         ),
  ///       );
  ///     },
  ///   );
  /// }
  /// ```
  /// {@end-tool}
  ///
  /// A less elegant but more expedient solution is to assign a [GlobalKey] to the
  /// [ScaffoldMessenger], then use the `key.currentState` property to obtain the
  /// [ScaffoldMessengerState] rather than using the [ScaffoldMessenger.of]
  /// function. The [MaterialApp.scaffoldMessengerKey] refers to the root
  /// ScaffoldMessenger that is provided by default.
  ///
143
  /// {@tool dartpad --template=freeform}
144 145 146 147 148 149 150 151 152 153 154
  /// Sometimes [SnackBar]s are produced by code that doesn't have ready access
  /// to a valid [BuildContext]. One such example of this is when you show a
  /// SnackBar from a method outside of the `build` function. In these
  /// cases, you can assign a [GlobalKey] to the [ScaffoldMessenger]. This
  /// example shows a key being used to obtain the [ScaffoldMessengerState]
  /// provided by the [MaterialApp].
  ///
  /// ```dart imports
  /// import 'package:flutter/material.dart';
  /// ```
  /// ```dart
155
  /// void main() => runApp(const MyApp());
156 157
  ///
  /// class MyApp extends StatefulWidget {
158 159
  ///   const MyApp({Key? key}) : super(key: key);
  ///
160
  ///   @override
161
  ///  State<MyApp> createState() => _MyAppState();
162 163 164 165 166 167 168 169 170 171 172
  /// }
  ///
  /// class _MyAppState extends State<MyApp> {
  ///   final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
  ///   int _counter = 0;
  ///
  ///   void _incrementCounter() {
  ///     setState(() {
  ///       _counter++;
  ///     });
  ///     if (_counter % 10 == 0) {
173
  ///       _scaffoldMessengerKey.currentState!.showSnackBar(const SnackBar(
174 175 176 177 178 179 180 181 182 183
  ///         content: Text('A multiple of ten!'),
  ///       ));
  ///     }
  ///   }
  ///
  ///   @override
  ///   Widget build(BuildContext context) {
  ///     return MaterialApp(
  ///       scaffoldMessengerKey: _scaffoldMessengerKey,
  ///       home: Scaffold(
184
  ///         appBar: AppBar(title: const Text('ScaffoldMessenger Demo')),
185 186 187 188
  ///         body: Center(
  ///           child: Column(
  ///             mainAxisAlignment: MainAxisAlignment.center,
  ///             children: <Widget>[
189
  ///               const Text(
190 191 192 193 194 195 196 197 198 199 200 201
  ///                 'You have pushed the button this many times:',
  ///               ),
  ///               Text(
  ///                 '$_counter',
  ///                 style: Theme.of(context).textTheme.headline4,
  ///               ),
  ///             ],
  ///           ),
  ///         ),
  ///         floatingActionButton: FloatingActionButton(
  ///           onPressed: _incrementCounter,
  ///           tooltip: 'Increment',
202
  ///           child: const Icon(Icons.add),
203 204 205 206 207 208 209 210 211
  ///         ),
  ///       ),
  ///     );
  ///   }
  /// }
  ///
  /// ```
  /// {@end-tool}
  ///
212 213 214
  /// If there is no [ScaffoldMessenger] in scope, then this will assert in
  /// debug mode, and throw an exception in release mode.
  ///
215 216
  /// See also:
  ///
217 218
  ///  * [maybeOf], which is a similar function but will return null instead of
  ///    throwing if there is no [ScaffoldMessenger] ancestor.
219 220
  ///  * [debugCheckHasScaffoldMessenger], which asserts that the given context
  ///    has a [ScaffoldMessenger] ancestor.
221
  static ScaffoldMessengerState of(BuildContext context) {
222
    assert(context != null);
223 224 225 226 227
    assert(debugCheckHasScaffoldMessenger(context));

    final _ScaffoldMessengerScope scope = context.dependOnInheritedWidgetOfExactType<_ScaffoldMessengerScope>()!;
    return scope._scaffoldMessengerState;
  }
228

229 230 231 232 233 234 235 236 237 238 239
  /// The state from the closest instance of this class that encloses the given
  /// context, if any.
  ///
  /// Will return null if a [ScaffoldMessenger] is not found in the given context.
  ///
  /// See also:
  ///
  ///  * [of], which is a similar function, except that it will throw an
  ///    exception if a [ScaffoldMessenger] is not found in the given context.
  static ScaffoldMessengerState? maybeOf(BuildContext context) {
    assert(context != null);
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

    final _ScaffoldMessengerScope? scope = context.dependOnInheritedWidgetOfExactType<_ScaffoldMessengerScope>();
    return scope?._scaffoldMessengerState;
  }

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

/// State for a [ScaffoldMessenger].
///
/// A [ScaffoldMessengerState] object can be used to [showSnackBar] for every
/// registered [Scaffold] that is a descendant of the associated
/// [ScaffoldMessenger]. Scaffolds will register to receive [SnackBar]s from
/// their closest ScaffoldMessenger ancestor.
///
/// Typically obtained via [ScaffoldMessenger.of].
class ScaffoldMessengerState extends State<ScaffoldMessenger> with TickerProviderStateMixin {
  final LinkedHashSet<ScaffoldState> _scaffolds = LinkedHashSet<ScaffoldState>();
  final Queue<ScaffoldFeatureController<SnackBar, SnackBarClosedReason>> _snackBars = Queue<ScaffoldFeatureController<SnackBar, SnackBarClosedReason>>();
  AnimationController? _snackBarController;
  Timer? _snackBarTimer;
  bool? _accessibleNavigation;

  @override
  void didChangeDependencies() {
266
    final MediaQueryData mediaQuery = MediaQuery.of(context);
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    // If we transition from accessible navigation to non-accessible navigation
    // and there is a SnackBar that would have timed out that has already
    // completed its timer, dismiss that SnackBar. If the timer hasn't finished
    // yet, let it timeout as normal.
    if (_accessibleNavigation == true
        && !mediaQuery.accessibleNavigation
        && _snackBarTimer != null
        && !_snackBarTimer!.isActive) {
      hideCurrentSnackBar(reason: SnackBarClosedReason.timeout);
    }
    _accessibleNavigation = mediaQuery.accessibleNavigation;
    super.didChangeDependencies();
  }

  void _register(ScaffoldState scaffold) {
    _scaffolds.add(scaffold);
283
    if (_snackBars.isNotEmpty && _isRoot(scaffold)) {
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
      scaffold._updateSnackBar();
    }
  }

  void _unregister(ScaffoldState scaffold) {
    final bool removed = _scaffolds.remove(scaffold);
    // ScaffoldStates should only be removed once.
    assert(removed);
  }

  /// Shows  a [SnackBar] across all registered [Scaffold]s.
  ///
  /// A scaffold can show at most one snack bar at a time. If this function is
  /// called while another snack bar is already visible, the given snack bar
  /// will be added to a queue and displayed after the earlier snack bars have
  /// closed.
  ///
  /// To control how long a [SnackBar] remains visible, use [SnackBar.duration].
  ///
  /// To remove the [SnackBar] with an exit animation, use [hideCurrentSnackBar]
  /// or call [ScaffoldFeatureController.close] on the returned
  /// [ScaffoldFeatureController]. To remove a [SnackBar] suddenly (without an
  /// animation), use [removeCurrentSnackBar].
  ///
  /// See [ScaffoldMessenger.of] for information about how to obtain the
  /// [ScaffoldMessengerState].
  ///
311
  /// {@tool dartpad --template=stateless_widget_scaffold_center}
312 313 314 315 316 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 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
  ///
  /// Here is an example of showing a [SnackBar] when the user presses a button.
  ///
  /// ```dart
  ///   Widget build(BuildContext context) {
  ///     return OutlinedButton(
  ///       onPressed: () {
  ///         ScaffoldMessenger.of(context).showSnackBar(
  ///           const SnackBar(
  ///             content: Text('A SnackBar has been shown.'),
  ///           ),
  ///         );
  ///       },
  ///       child: const Text('Show SnackBar'),
  ///     );
  ///   }
  /// ```
  /// {@end-tool}
  ScaffoldFeatureController<SnackBar, SnackBarClosedReason> showSnackBar(SnackBar snackBar) {
    _snackBarController ??= SnackBar.createAnimationController(vsync: this)
      ..addStatusListener(_handleStatusChanged);
    if (_snackBars.isEmpty) {
      assert(_snackBarController!.isDismissed);
      _snackBarController!.forward();
    }
    late ScaffoldFeatureController<SnackBar, SnackBarClosedReason> controller;
    controller = ScaffoldFeatureController<SnackBar, SnackBarClosedReason>._(
      // We provide a fallback key so that if back-to-back snackbars happen to
      // match in structure, material ink splashes and highlights don't survive
      // from one to the next.
      snackBar.withAnimation(_snackBarController!, fallbackKey: UniqueKey()),
      Completer<SnackBarClosedReason>(),
        () {
          assert(_snackBars.first == controller);
          hideCurrentSnackBar(reason: SnackBarClosedReason.hide);
        },
      null, // SnackBar doesn't use a builder function so setState() wouldn't rebuild it
    );
    setState(() {
      _snackBars.addLast(controller);
    });
    _updateScaffolds();
    return controller;
  }

  void _handleStatusChanged(AnimationStatus status) {
    switch (status) {
      case AnimationStatus.dismissed:
        assert(_snackBars.isNotEmpty);
        setState(() {
          _snackBars.removeFirst();
        });
        _updateScaffolds();
        if (_snackBars.isNotEmpty) {
          _snackBarController!.forward();
        }
        break;
      case AnimationStatus.completed:
        setState(() {
          assert(_snackBarTimer == null);
          // build will create a new timer if necessary to dismiss the snackBar.
        });
        _updateScaffolds();
        break;
      case AnimationStatus.forward:
        break;
      case AnimationStatus.reverse:
        break;
    }
  }

  void _updateScaffolds() {
    for (final ScaffoldState scaffold in _scaffolds) {
385 386
      if (_isRoot(scaffold))
        scaffold._updateSnackBar();
387 388 389
    }
  }

390 391 392 393 394 395 396
  // Nested Scaffolds are handled by the ScaffoldMessenger by only presenting a
  // SnackBar in the root Scaffold of the nested set.
  bool _isRoot(ScaffoldState scaffold) {
    final ScaffoldState? parent = scaffold.context.findAncestorStateOfType<ScaffoldState>();
    return parent == null || !_scaffolds.contains(parent);
  }

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
  /// Removes the current [SnackBar] (if any) immediately from registered
  /// [Scaffold]s.
  ///
  /// The removed snack bar does not run its normal exit animation. If there are
  /// any queued snack bars, they begin their entrance animation immediately.
  void removeCurrentSnackBar({ SnackBarClosedReason reason = SnackBarClosedReason.remove }) {
    assert(reason != null);
    if (_snackBars.isEmpty)
      return;
    final Completer<SnackBarClosedReason> completer = _snackBars.first._completer;
    if (!completer.isCompleted)
      completer.complete(reason);
    _snackBarTimer?.cancel();
    _snackBarTimer = null;
    // This will trigger the animation's status callback.
    _snackBarController!.value = 0.0;
  }

  /// Removes the current [SnackBar] by running its normal exit animation.
  ///
  /// The closed completer is called after the animation is complete.
  void hideCurrentSnackBar({ SnackBarClosedReason reason = SnackBarClosedReason.hide }) {
    assert(reason != null);
    if (_snackBars.isEmpty || _snackBarController!.status == AnimationStatus.dismissed)
      return;
    final Completer<SnackBarClosedReason> completer = _snackBars.first._completer;
    if (_accessibleNavigation!) {
      _snackBarController!.value = 0.0;
      completer.complete(reason);
    } else {
      _snackBarController!.reverse().then<void>((void value) {
        assert(mounted);
        if (!completer.isCompleted)
          completer.complete(reason);
      });
    }
    _snackBarTimer?.cancel();
    _snackBarTimer = null;
  }

437 438 439 440 441 442 443 444 445 446 447
  /// Removes all the snackBars currently in queue by clearing the queue
  /// and running normal exit animation on the current snackBar.
  void clearSnackBars() {
    if (_snackBars.isEmpty || _snackBarController!.status == AnimationStatus.dismissed)
      return;
    final ScaffoldFeatureController<SnackBar, SnackBarClosedReason> currentSnackbar = _snackBars.first;
    _snackBars.clear();
    _snackBars.add(currentSnackbar);
    hideCurrentSnackBar();
  }

448 449 450
  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasMediaQuery(context));
451
    final MediaQueryData mediaQuery = MediaQuery.of(context);
452 453 454
    _accessibleNavigation = mediaQuery.accessibleNavigation;

    if (_snackBars.isNotEmpty) {
455
      final ModalRoute<dynamic>? route = ModalRoute.of(context);
456 457 458 459
      if (route == null || route.isCurrent) {
        if (_snackBarController!.isCompleted && _snackBarTimer == null) {
          final SnackBar snackBar = _snackBars.first._widget;
          _snackBarTimer = Timer(snackBar.duration, () {
460 461 462 463
            assert(
              _snackBarController!.status == AnimationStatus.forward ||
                _snackBarController!.status == AnimationStatus.completed,
            );
464
            // Look up MediaQuery again in case the setting changed.
465
            final MediaQueryData mediaQuery = MediaQuery.of(context);
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
            if (mediaQuery.accessibleNavigation && snackBar.action != null)
              return;
            hideCurrentSnackBar(reason: SnackBarClosedReason.timeout);
          });
        }
      }
    }

    return _ScaffoldMessengerScope(
      scaffoldMessengerState: this,
      child: widget.child,
    );
  }

  @override
  void dispose() {
    _snackBarController?.dispose();
    _snackBarTimer?.cancel();
    _snackBarTimer = null;
    super.dispose();
  }
}

class _ScaffoldMessengerScope extends InheritedWidget {
  const _ScaffoldMessengerScope({
    Key? key,
    required Widget child,
    required ScaffoldMessengerState scaffoldMessengerState,
  }) : _scaffoldMessengerState = scaffoldMessengerState,
      super(key: key, child: child);

  final ScaffoldMessengerState _scaffoldMessengerState;

  @override
  bool updateShouldNotify(_ScaffoldMessengerScope old) => _scaffoldMessengerState != old._scaffoldMessengerState;
}

503 504
/// The geometry of the [Scaffold] after all its contents have been laid out
/// except the [FloatingActionButton].
505
///
506
/// The [Scaffold] passes this pre-layout geometry to its
507
/// [FloatingActionButtonLocation], which produces an [Offset] that the
508
/// [Scaffold] uses to position the [FloatingActionButton].
509
///
510 511 512 513 514 515 516
/// For a description of the [Scaffold]'s geometry after it has
/// finished laying out, see the [ScaffoldGeometry].
@immutable
class ScaffoldPrelayoutGeometry {
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  const ScaffoldPrelayoutGeometry({
517 518 519 520 521 522 523 524 525
    required this.bottomSheetSize,
    required this.contentBottom,
    required this.contentTop,
    required this.floatingActionButtonSize,
    required this.minInsets,
    required this.minViewPadding,
    required this.scaffoldSize,
    required this.snackBarSize,
    required this.textDirection,
526 527 528
  });

  /// The [Size] of [Scaffold.floatingActionButton].
529
  ///
530 531 532 533
  /// If [Scaffold.floatingActionButton] is null, this will be [Size.zero].
  final Size floatingActionButtonSize;

  /// The [Size] of the [Scaffold]'s [BottomSheet].
534
  ///
535 536 537 538 539 540
  /// If the [Scaffold] is not currently showing a [BottomSheet],
  /// this will be [Size.zero].
  final Size bottomSheetSize;

  /// The vertical distance from the Scaffold's origin to the bottom of
  /// [Scaffold.body].
541
  ///
542 543 544 545
  /// This is useful in a [FloatingActionButtonLocation] designed to
  /// place the [FloatingActionButton] at the bottom of the screen, while
  /// keeping it above the [BottomSheet], the [Scaffold.bottomNavigationBar],
  /// or the keyboard.
546
  ///
Ian Hickson's avatar
Ian Hickson committed
547 548
  /// The [Scaffold.body] is laid out with respect to [minInsets] already. This
  /// means that a [FloatingActionButtonLocation] does not need to factor in
549 550
  /// [EdgeInsets.bottom] of [minInsets] when aligning a [FloatingActionButton]
  /// to [contentBottom].
551 552 553 554
  final double contentBottom;

  /// The vertical distance from the [Scaffold]'s origin to the top of
  /// [Scaffold.body].
555
  ///
556 557 558
  /// This is useful in a [FloatingActionButtonLocation] designed to
  /// place the [FloatingActionButton] at the top of the screen, while
  /// keeping it below the [Scaffold.appBar].
559
  ///
Ian Hickson's avatar
Ian Hickson committed
560 561
  /// The [Scaffold.body] is laid out with respect to [minInsets] already. This
  /// means that a [FloatingActionButtonLocation] does not need to factor in
562 563
  /// [EdgeInsets.top] of [minInsets] when aligning a [FloatingActionButton] to
  /// [contentTop].
564 565 566 567
  final double contentTop;

  /// The minimum padding to inset the [FloatingActionButton] by for it
  /// to remain visible.
568
  ///
569
  /// This value is the result of calling [MediaQueryData.padding] in the
570 571 572
  /// [Scaffold]'s [BuildContext],
  /// and is useful for insetting the [FloatingActionButton] to avoid features like
  /// the system status bar or the keyboard.
573
  ///
574 575
  /// If [Scaffold.resizeToAvoidBottomInset] is set to false,
  /// [EdgeInsets.bottom] of [minInsets] will be 0.0.
576 577
  final EdgeInsets minInsets;

578 579 580
  /// The minimum padding to inset interactive elements to be within a safe,
  /// un-obscured space.
  ///
581
  /// This value reflects the [MediaQueryData.viewPadding] of the [Scaffold]'s
582
  /// [BuildContext] when [Scaffold.resizeToAvoidBottomInset] is false or and
583
  /// the [MediaQueryData.viewInsets] > 0.0. This helps distinguish between
584 585 586 587
  /// different types of obstructions on the screen, such as software keyboards
  /// and physical device notches.
  final EdgeInsets minViewPadding;

588
  /// The [Size] of the whole [Scaffold].
589 590
  ///
  /// If the [Size] of the [Scaffold]'s contents is modified by values such as
591
  /// [Scaffold.resizeToAvoidBottomInset] or the keyboard opening, then the
592
  /// [scaffoldSize] will not reflect those changes.
593
  ///
594 595 596 597
  /// This means that [FloatingActionButtonLocation]s designed to reposition
  /// the [FloatingActionButton] based on events such as the keyboard popping
  /// up should use [minInsets] to make sure that the [FloatingActionButton] is
  /// inset by enough to remain visible.
598
  ///
599 600
  /// See [minInsets] and [MediaQueryData.padding] for more information on the
  /// appropriate insets to apply.
601 602 603
  final Size scaffoldSize;

  /// The [Size] of the [Scaffold]'s [SnackBar].
604
  ///
605 606 607 608 609 610 611 612 613 614 615 616 617
  /// If the [Scaffold] is not showing a [SnackBar], this will be [Size.zero].
  final Size snackBarSize;

  /// The [TextDirection] of the [Scaffold]'s [BuildContext].
  final TextDirection textDirection;
}

/// A snapshot of a transition between two [FloatingActionButtonLocation]s.
///
/// [ScaffoldState] uses this to seamlessly change transition animations
/// when a running [FloatingActionButtonLocation] transition is interrupted by a new transition.
@immutable
class _TransitionSnapshotFabLocation extends FloatingActionButtonLocation {
618

619 620 621 622 623 624 625 626 627 628
  const _TransitionSnapshotFabLocation(this.begin, this.end, this.animator, this.progress);

  final FloatingActionButtonLocation begin;
  final FloatingActionButtonLocation end;
  final FloatingActionButtonAnimator animator;
  final double progress;

  @override
  Offset getOffset(ScaffoldPrelayoutGeometry scaffoldGeometry) {
    return animator.getOffset(
629 630
      begin: begin.getOffset(scaffoldGeometry),
      end: end.getOffset(scaffoldGeometry),
631 632 633 634 635 636
      progress: progress,
    );
  }

  @override
  String toString() {
637
    return '${objectRuntimeType(this, '_TransitionSnapshotFabLocation')}(begin: $begin, end: $end, progress: $progress)';
638 639 640 641
  }
}

/// Geometry information for [Scaffold] components after layout is finished.
642
///
643 644
/// To get a [ValueNotifier] for the scaffold geometry of a given
/// [BuildContext], use [Scaffold.geometryOf].
645
///
646 647
/// The ScaffoldGeometry is only available during the paint phase, because
/// its value is computed during the animation and layout phases prior to painting.
648
///
649 650 651
/// For an example of using the [ScaffoldGeometry], see the [BottomAppBar],
/// which uses the [ScaffoldGeometry] to paint a notch around the
/// [FloatingActionButton].
652 653
///
/// For information about the [Scaffold]'s geometry that is used while laying
654
/// out the [FloatingActionButton], see [ScaffoldPrelayoutGeometry].
655 656
@immutable
class ScaffoldGeometry {
657
  /// Create an object that describes the geometry of a [Scaffold].
658 659 660 661 662
  const ScaffoldGeometry({
    this.bottomNavigationBarTop,
    this.floatingActionButtonArea,
  });

663 664
  /// The distance from the [Scaffold]'s top edge to the top edge of the
  /// rectangle in which the [Scaffold.bottomNavigationBar] bar is laid out.
665
  ///
666
  /// Null if [Scaffold.bottomNavigationBar] is null.
667
  final double? bottomNavigationBarTop;
668

669
  /// The [Scaffold.floatingActionButton]'s bounding rectangle.
670 671
  ///
  /// This is null when there is no floating action button showing.
672
  final Rect? floatingActionButtonArea;
673

674
  ScaffoldGeometry _scaleFloatingActionButton(double scaleFactor) {
675 676 677
    if (scaleFactor == 1.0)
      return this;

678
    if (scaleFactor == 0.0) {
679
      return ScaffoldGeometry(
680 681 682
        bottomNavigationBarTop: bottomNavigationBarTop,
      );
    }
683

684
    final Rect scaledButton = Rect.lerp(
685
      floatingActionButtonArea!.center & Size.zero,
686
      floatingActionButtonArea,
687
      scaleFactor,
688
    )!;
689 690 691 692 693 694
    return copyWith(floatingActionButtonArea: scaledButton);
  }

  /// Creates a copy of this [ScaffoldGeometry] but with the given fields replaced with
  /// the new values.
  ScaffoldGeometry copyWith({
695 696
    double? bottomNavigationBarTop,
    Rect? floatingActionButtonArea,
697
  }) {
698
    return ScaffoldGeometry(
699 700
      bottomNavigationBarTop: bottomNavigationBarTop ?? this.bottomNavigationBarTop,
      floatingActionButtonArea: floatingActionButtonArea ?? this.floatingActionButtonArea,
701 702
    );
  }
703 704
}

705 706 707
class _ScaffoldGeometryNotifier extends ChangeNotifier implements ValueListenable<ScaffoldGeometry> {
  _ScaffoldGeometryNotifier(this.geometry, this.context)
    : assert (context != null);
708 709

  final BuildContext context;
710
  double? floatingActionButtonScale;
711
  ScaffoldGeometry geometry;
712 713 714 715

  @override
  ScaffoldGeometry get value {
    assert(() {
716 717
      final RenderObject? renderObject = context.findRenderObject();
      if (renderObject == null || !renderObject.owner!.debugDoingPaint)
718
        throw FlutterError(
719
            'Scaffold.geometryOf() must only be accessed during the paint phase.\n'
720
            'The ScaffoldGeometry is only available during the paint phase, because '
721
            'its value is computed during the animation and layout phases prior to painting.',
722 723 724
        );
      return true;
    }());
725
    return geometry._scaleFloatingActionButton(floatingActionButtonScale!);
726 727 728
  }

  void _updateWith({
729 730 731
    double? bottomNavigationBarTop,
    Rect? floatingActionButtonArea,
    double? floatingActionButtonScale,
732
  }) {
733
    this.floatingActionButtonScale = floatingActionButtonScale ?? this.floatingActionButtonScale;
734 735 736
    geometry = geometry.copyWith(
      bottomNavigationBarTop: bottomNavigationBarTop,
      floatingActionButtonArea: floatingActionButtonArea,
737
    );
738
    notifyListeners();
739 740 741
  }
}

742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
// Used to communicate the height of the Scaffold's bottomNavigationBar and
// persistentFooterButtons to the LayoutBuilder which builds the Scaffold's body.
//
// Scaffold expects a _BodyBoxConstraints to be passed to the _BodyBuilder
// widget's LayoutBuilder, see _ScaffoldLayout.performLayout(). The BoxConstraints
// methods that construct new BoxConstraints objects, like copyWith() have not
// been overridden here because we expect the _BodyBoxConstraintsObject to be
// passed along unmodified to the LayoutBuilder. If that changes in the future
// then _BodyBuilder will assert.
class _BodyBoxConstraints extends BoxConstraints {
  const _BodyBoxConstraints({
    double minWidth = 0.0,
    double maxWidth = double.infinity,
    double minHeight = 0.0,
    double maxHeight = double.infinity,
757 758
    required this.bottomWidgetsHeight,
    required this.appBarHeight,
759 760
  }) : assert(bottomWidgetsHeight != null),
       assert(bottomWidgetsHeight >= 0),
761 762
       assert(appBarHeight != null),
       assert(appBarHeight >= 0),
763
       super(minWidth: minWidth, maxWidth: maxWidth, minHeight: minHeight, maxHeight: maxHeight);
764 765

  final double bottomWidgetsHeight;
766
  final double appBarHeight;
767 768 769 770 771 772

  // RenderObject.layout() will only short-circuit its call to its performLayout
  // method if the new layout constraints are not == to the current constraints.
  // If the height of the bottom widgets has changed, even though the constraints'
  // min and max values have not, we still want performLayout to happen.
  @override
773
  bool operator ==(Object other) {
774 775
    if (super != other)
      return false;
776 777 778
    return other is _BodyBoxConstraints
        && other.bottomWidgetsHeight == bottomWidgetsHeight
        && other.appBarHeight == appBarHeight;
779 780 781 782
  }

  @override
  int get hashCode {
783
    return hashValues(super.hashCode, bottomWidgetsHeight, appBarHeight);
784 785 786 787 788 789 790 791 792 793
  }
}

// Used when Scaffold.extendBody is true to wrap the scaffold's body in a MediaQuery
// whose padding accounts for the height of the bottomNavigationBar and/or the
// persistentFooterButtons.
//
// The bottom widgets' height is passed along via the _BodyBoxConstraints parameter.
// The constraints parameter is constructed in_ScaffoldLayout.performLayout().
class _BodyBuilder extends StatelessWidget {
794
  const _BodyBuilder({
795 796 797 798
    Key? key,
    required this.extendBody,
    required this.extendBodyBehindAppBar,
    required this.body,
799 800 801 802
  }) : assert(extendBody != null),
       assert(extendBodyBehindAppBar != null),
       assert(body != null),
       super(key: key);
803 804

  final Widget body;
805 806
  final bool extendBody;
  final bool extendBodyBehindAppBar;
807 808 809

  @override
  Widget build(BuildContext context) {
810 811 812
    if (!extendBody && !extendBodyBehindAppBar)
      return body;

813 814
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
815
        final _BodyBoxConstraints bodyConstraints = constraints as _BodyBoxConstraints;
816
        final MediaQueryData metrics = MediaQuery.of(context);
817 818 819 820 821 822 823 824 825

        final double bottom = extendBody
          ? math.max(metrics.padding.bottom, bodyConstraints.bottomWidgetsHeight)
          : metrics.padding.bottom;

        final double top = extendBodyBehindAppBar
          ? math.max(metrics.padding.top, bodyConstraints.appBarHeight)
          : metrics.padding.top;

826 827 828
        return MediaQuery(
          data: metrics.copyWith(
            padding: metrics.padding.copyWith(
829 830
              top: top,
              bottom: bottom,
831 832 833 834 835 836 837 838 839
            ),
          ),
          child: body,
        );
      },
    );
  }
}

840
class _ScaffoldLayout extends MultiChildLayoutDelegate {
841
  _ScaffoldLayout({
842 843 844 845
    required this.minInsets,
    required this.minViewPadding,
    required this.textDirection,
    required this.geometryNotifier,
846
    // for floating action button
847 848 849 850 851 852 853 854
    required this.previousFloatingActionButtonLocation,
    required this.currentFloatingActionButtonLocation,
    required this.floatingActionButtonMoveAnimationProgress,
    required this.floatingActionButtonMotionAnimator,
    required this.isSnackBarFloating,
    required this.snackBarWidth,
    required this.extendBody,
    required this.extendBodyBehindAppBar,
855 856 857 858
  }) : assert(minInsets != null),
       assert(textDirection != null),
       assert(geometryNotifier != null),
       assert(previousFloatingActionButtonLocation != null),
859
       assert(currentFloatingActionButtonLocation != null),
860 861
       assert(extendBody != null),
       assert(extendBodyBehindAppBar != null);
862

863
  final bool extendBody;
864
  final bool extendBodyBehindAppBar;
865
  final EdgeInsets minInsets;
866
  final EdgeInsets minViewPadding;
867
  final TextDirection textDirection;
868
  final _ScaffoldGeometryNotifier geometryNotifier;
869

870 871 872 873 874
  final FloatingActionButtonLocation previousFloatingActionButtonLocation;
  final FloatingActionButtonLocation currentFloatingActionButtonLocation;
  final double floatingActionButtonMoveAnimationProgress;
  final FloatingActionButtonAnimator floatingActionButtonMotionAnimator;

875
  final bool isSnackBarFloating;
876
  final double? snackBarWidth;
877

878
  @override
879
  void performLayout(Size size) {
880
    final BoxConstraints looseConstraints = BoxConstraints.loose(size);
881

882
    // This part of the layout has the same effect as putting the app bar and
883
    // body in a column and making the body flexible. What's different is that
884
    // in this case the app bar appears _after_ the body in the stacking order,
885
    // so the app bar's shadow is drawn on top of the body.
886

887
    final BoxConstraints fullWidthConstraints = looseConstraints.tighten(width: size.width);
888
    final double bottom = size.height;
889
    double contentTop = 0.0;
890
    double bottomWidgetsHeight = 0.0;
891
    double appBarHeight = 0.0;
892

893
    if (hasChild(_ScaffoldSlot.appBar)) {
894 895
      appBarHeight = layoutChild(_ScaffoldSlot.appBar, fullWidthConstraints).height;
      contentTop = extendBodyBehindAppBar ? 0.0 : appBarHeight;
896
      positionChild(_ScaffoldSlot.appBar, Offset.zero);
897 898
    }

899
    double? bottomNavigationBarTop;
900 901
    if (hasChild(_ScaffoldSlot.bottomNavigationBar)) {
      final double bottomNavigationBarHeight = layoutChild(_ScaffoldSlot.bottomNavigationBar, fullWidthConstraints).height;
902
      bottomWidgetsHeight += bottomNavigationBarHeight;
903
      bottomNavigationBarTop = math.max(0.0, bottom - bottomWidgetsHeight);
904
      positionChild(_ScaffoldSlot.bottomNavigationBar, Offset(0.0, bottomNavigationBarTop));
905 906
    }

907
    if (hasChild(_ScaffoldSlot.persistentFooter)) {
908
      final BoxConstraints footerConstraints = BoxConstraints(
Ian Hickson's avatar
Ian Hickson committed
909
        maxWidth: fullWidthConstraints.maxWidth,
910
        maxHeight: math.max(0.0, bottom - bottomWidgetsHeight - contentTop),
Ian Hickson's avatar
Ian Hickson committed
911 912
      );
      final double persistentFooterHeight = layoutChild(_ScaffoldSlot.persistentFooter, footerConstraints).height;
913
      bottomWidgetsHeight += persistentFooterHeight;
914
      positionChild(_ScaffoldSlot.persistentFooter, Offset(0.0, math.max(0.0, bottom - bottomWidgetsHeight)));
915 916
    }

917 918 919
    // Set the content bottom to account for the greater of the height of any
    // bottom-anchored material widgets or of the keyboard or other
    // bottom-anchored system UI.
920
    final double contentBottom = math.max(0.0, bottom - math.max(minInsets.bottom, bottomWidgetsHeight));
921

922
    if (hasChild(_ScaffoldSlot.body)) {
923 924 925 926
      double bodyMaxHeight = math.max(0.0, contentBottom - contentTop);

      if (extendBody) {
        bodyMaxHeight += bottomWidgetsHeight;
927
        bodyMaxHeight = bodyMaxHeight.clamp(0.0, looseConstraints.maxHeight - contentTop);
928 929 930 931
        assert(bodyMaxHeight <= math.max(0.0, looseConstraints.maxHeight - contentTop));
      }

      final BoxConstraints bodyConstraints = _BodyBoxConstraints(
932
        maxWidth: fullWidthConstraints.maxWidth,
933 934
        maxHeight: bodyMaxHeight,
        bottomWidgetsHeight: extendBody ? bottomWidgetsHeight : 0.0,
935
        appBarHeight: appBarHeight,
936
      );
937
      layoutChild(_ScaffoldSlot.body, bodyConstraints);
938
      positionChild(_ScaffoldSlot.body, Offset(0.0, contentTop));
939
    }
940 941

    // The BottomSheet and the SnackBar are anchored to the bottom of the parent,
942 943 944 945
    // they're as wide as the parent and are given their intrinsic height. The
    // only difference is that SnackBar appears on the top side of the
    // BottomNavigationBar while the BottomSheet is stacked on top of it.
    //
946 947
    // If all three elements are present then either the center of the FAB straddles
    // the top edge of the BottomSheet or the bottom of the FAB is
948
    // kFloatingActionButtonMargin above the SnackBar, whichever puts the FAB
949 950
    // the farthest above the bottom of the parent. If only the FAB is has a
    // non-zero height then it's inset from the parent's right and bottom edges
951
    // by kFloatingActionButtonMargin.
952

953 954
    Size bottomSheetSize = Size.zero;
    Size snackBarSize = Size.zero;
955 956 957 958 959 960 961 962
    if (hasChild(_ScaffoldSlot.bodyScrim)) {
      final BoxConstraints bottomSheetScrimConstraints = BoxConstraints(
        maxWidth: fullWidthConstraints.maxWidth,
        maxHeight: contentBottom,
      );
      layoutChild(_ScaffoldSlot.bodyScrim, bottomSheetScrimConstraints);
      positionChild(_ScaffoldSlot.bodyScrim, Offset.zero);
    }
963

964 965 966 967 968 969
    // Set the size of the SnackBar early if the behavior is fixed so
    // the FAB can be positioned correctly.
    if (hasChild(_ScaffoldSlot.snackBar) && !isSnackBarFloating) {
      snackBarSize = layoutChild(_ScaffoldSlot.snackBar, fullWidthConstraints);
    }

970
    if (hasChild(_ScaffoldSlot.bottomSheet)) {
971
      final BoxConstraints bottomSheetConstraints = BoxConstraints(
Ian Hickson's avatar
Ian Hickson committed
972 973 974 975
        maxWidth: fullWidthConstraints.maxWidth,
        maxHeight: math.max(0.0, contentBottom - contentTop),
      );
      bottomSheetSize = layoutChild(_ScaffoldSlot.bottomSheet, bottomSheetConstraints);
976
      positionChild(_ScaffoldSlot.bottomSheet, Offset((size.width - bottomSheetSize.width) / 2.0, contentBottom - bottomSheetSize.height));
977 978
    }

979
    late Rect floatingActionButtonRect;
980
    if (hasChild(_ScaffoldSlot.floatingActionButton)) {
981
      final Size fabSize = layoutChild(_ScaffoldSlot.floatingActionButton, looseConstraints);
982

983 984
      // To account for the FAB position being changed, we'll animate between
      // the old and new positions.
985
      final ScaffoldPrelayoutGeometry currentGeometry = ScaffoldPrelayoutGeometry(
986 987
        bottomSheetSize: bottomSheetSize,
        contentBottom: contentBottom,
988 989 990
        /// [appBarHeight] should be used instead of [contentTop] because
        /// ScaffoldPrelayoutGeometry.contentTop must not be affected by [extendBodyBehindAppBar].
        contentTop: appBarHeight,
991 992 993 994 995
        floatingActionButtonSize: fabSize,
        minInsets: minInsets,
        scaffoldSize: size,
        snackBarSize: snackBarSize,
        textDirection: textDirection,
996
        minViewPadding: minViewPadding,
997 998 999 1000
      );
      final Offset currentFabOffset = currentFloatingActionButtonLocation.getOffset(currentGeometry);
      final Offset previousFabOffset = previousFloatingActionButtonLocation.getOffset(currentGeometry);
      final Offset fabOffset = floatingActionButtonMotionAnimator.getOffset(
1001 1002
        begin: previousFabOffset,
        end: currentFabOffset,
1003 1004 1005 1006
        progress: floatingActionButtonMoveAnimationProgress,
      );
      positionChild(_ScaffoldSlot.floatingActionButton, fabOffset);
      floatingActionButtonRect = fabOffset & fabSize;
1007
    }
1008

1009
    if (hasChild(_ScaffoldSlot.snackBar)) {
1010
      final bool hasCustomWidth = snackBarWidth != null && snackBarWidth! < size.width;
1011
      if (snackBarSize == Size.zero) {
1012 1013 1014 1015
        snackBarSize = layoutChild(
          _ScaffoldSlot.snackBar,
          hasCustomWidth ? looseConstraints : fullWidthConstraints,
        );
1016
      }
1017

1018
      final double snackBarYOffsetBase;
1019 1020
      if (floatingActionButtonRect.size != Size.zero && isSnackBarFloating) {
        snackBarYOffsetBase = floatingActionButtonRect.top;
1021
      } else {
1022 1023 1024 1025 1026 1027 1028 1029 1030
        // SnackBarBehavior.fixed applies a SafeArea automatically.
        // SnackBarBehavior.floating does not since the positioning is affected
        // if there is a FloatingActionButton (see condition above). If there is
        // no FAB, make sure we account for safe space when the SnackBar is
        // floating.
        final double safeYOffsetBase = size.height - minViewPadding.bottom;
        snackBarYOffsetBase = isSnackBarFloating
          ? math.min(contentBottom, safeYOffsetBase)
          : contentBottom;
1031 1032
      }

1033
      final double xOffset = hasCustomWidth ? (size.width - snackBarWidth!) / 2 : 0.0;
1034
      positionChild(_ScaffoldSlot.snackBar, Offset(xOffset, snackBarYOffsetBase - snackBarSize.height));
1035 1036
    }

1037
    if (hasChild(_ScaffoldSlot.statusBar)) {
1038
      layoutChild(_ScaffoldSlot.statusBar, fullWidthConstraints.tighten(height: minInsets.top));
1039 1040 1041
      positionChild(_ScaffoldSlot.statusBar, Offset.zero);
    }

1042
    if (hasChild(_ScaffoldSlot.drawer)) {
1043
      layoutChild(_ScaffoldSlot.drawer, BoxConstraints.tight(size));
1044
      positionChild(_ScaffoldSlot.drawer, Offset.zero);
1045
    }
1046 1047

    if (hasChild(_ScaffoldSlot.endDrawer)) {
1048
      layoutChild(_ScaffoldSlot.endDrawer, BoxConstraints.tight(size));
1049 1050
      positionChild(_ScaffoldSlot.endDrawer, Offset.zero);
    }
1051 1052 1053 1054 1055

    geometryNotifier._updateWith(
      bottomNavigationBarTop: bottomNavigationBarTop,
      floatingActionButtonArea: floatingActionButtonRect,
    );
Hans Muller's avatar
Hans Muller committed
1056
  }
1057

1058
  @override
1059
  bool shouldRelayout(_ScaffoldLayout oldDelegate) {
1060 1061 1062 1063
    return oldDelegate.minInsets != minInsets
        || oldDelegate.textDirection != textDirection
        || oldDelegate.floatingActionButtonMoveAnimationProgress != floatingActionButtonMoveAnimationProgress
        || oldDelegate.previousFloatingActionButtonLocation != previousFloatingActionButtonLocation
1064 1065 1066
        || oldDelegate.currentFloatingActionButtonLocation != currentFloatingActionButtonLocation
        || oldDelegate.extendBody != extendBody
        || oldDelegate.extendBodyBehindAppBar != extendBodyBehindAppBar;
1067
  }
Hans Muller's avatar
Hans Muller committed
1068 1069
}

1070 1071 1072
/// Handler for scale and rotation animations in the [FloatingActionButton].
///
/// Currently, there are two types of [FloatingActionButton] animations:
1073
///
1074 1075 1076 1077
/// * Entrance/Exit animations, which this widget triggers
///   when the [FloatingActionButton] is added, updated, or removed.
/// * Motion animations, which are triggered by the [Scaffold]
///   when its [FloatingActionButtonLocation] is updated.
1078
class _FloatingActionButtonTransition extends StatefulWidget {
1079
  const _FloatingActionButtonTransition({
1080 1081 1082 1083 1084 1085
    Key? key,
    required this.child,
    required this.fabMoveAnimation,
    required this.fabMotionAnimator,
    required this.geometryNotifier,
    required this.currentController,
1086
  }) : assert(fabMoveAnimation != null),
1087
       assert(fabMotionAnimator != null),
1088
       assert(currentController != null),
1089
       super(key: key);
1090

1091
  final Widget? child;
1092 1093
  final Animation<double> fabMoveAnimation;
  final FloatingActionButtonAnimator fabMotionAnimator;
1094
  final _ScaffoldGeometryNotifier geometryNotifier;
1095

1096 1097 1098
  /// Controls the current child widget.child as it exits.
  final AnimationController currentController;

1099
  @override
1100
  _FloatingActionButtonTransitionState createState() => _FloatingActionButtonTransitionState();
1101 1102
}

1103
class _FloatingActionButtonTransitionState extends State<_FloatingActionButtonTransition> with TickerProviderStateMixin {
1104
  // The animations applied to the Floating Action Button when it is entering or exiting.
1105
  // Controls the previous widget.child as it exits.
1106 1107 1108
  late AnimationController _previousController;
  late Animation<double> _previousScaleAnimation;
  late Animation<double> _previousRotationAnimation;
1109
  // The animations to run, considering the widget's fabMoveAnimation and the current/previous entrance/exit animations.
1110 1111 1112 1113
  late Animation<double> _currentScaleAnimation;
  late Animation<double> _extendedCurrentScaleAnimation;
  late Animation<double> _currentRotationAnimation;
  Widget? _previousChild;
1114

1115
  @override
1116 1117
  void initState() {
    super.initState();
1118

1119
    _previousController = AnimationController(
1120
      duration: kFloatingActionButtonSegue,
1121
      vsync: this,
1122 1123
    )..addStatusListener(_handlePreviousAnimationStatusChanged);
    _updateAnimations();
1124

1125 1126 1127
    if (widget.child != null) {
      // If we start out with a child, have the child appear fully visible instead
      // of animating in.
1128
      widget.currentController.value = 1.0;
1129
    } else {
1130 1131 1132 1133
      // If we start without a child we update the geometry object with a
      // floating action button scale of 0, as it is not showing on the screen.
      _updateGeometryScale(0.0);
    }
1134 1135
  }

1136
  @override
1137
  void dispose() {
1138
    _previousController.dispose();
1139 1140 1141
    super.dispose();
  }

1142
  @override
1143
  void didUpdateWidget(_FloatingActionButtonTransition oldWidget) {
1144
    super.didUpdateWidget(oldWidget);
1145 1146 1147
    final bool oldChildIsNull = oldWidget.child == null;
    final bool newChildIsNull = widget.child == null;
    if (oldChildIsNull == newChildIsNull && oldWidget.child?.key == widget.child?.key)
1148
      return;
1149
    if (oldWidget.fabMotionAnimator != widget.fabMotionAnimator || oldWidget.fabMoveAnimation != widget.fabMoveAnimation) {
1150 1151 1152
      // Get the right scale and rotation animations to use for this widget.
      _updateAnimations();
    }
1153
    if (_previousController.status == AnimationStatus.dismissed) {
1154
      final double currentValue = widget.currentController.value;
1155
      if (currentValue == 0.0 || oldWidget.child == null) {
1156 1157 1158
        // The current child hasn't started its entrance animation yet. We can
        // just skip directly to the new child's entrance.
        _previousChild = null;
1159
        if (widget.child != null)
1160
          widget.currentController.forward();
1161 1162 1163 1164
      } else {
        // Otherwise, we need to copy the state from the current controller to
        // the previous controller and run an exit animation for the previous
        // widget before running the entrance animation for the new child.
1165
        _previousChild = oldWidget.child;
1166 1167 1168
        _previousController
          ..value = currentValue
          ..reverse();
1169
        widget.currentController.value = 0.0;
1170 1171 1172 1173
      }
    }
  }

1174 1175 1176 1177 1178
  static final Animatable<double> _entranceTurnTween = Tween<double>(
    begin: 1.0 - kFloatingActionButtonTurnInterval,
    end: 1.0,
  ).chain(CurveTween(curve: Curves.easeIn));

1179 1180
  void _updateAnimations() {
    // Get the animations for exit and entrance.
1181
    final CurvedAnimation previousExitScaleAnimation = CurvedAnimation(
1182 1183 1184
      parent: _previousController,
      curve: Curves.easeIn,
    );
1185 1186
    final Animation<double> previousExitRotationAnimation = Tween<double>(begin: 1.0, end: 1.0).animate(
      CurvedAnimation(
1187 1188 1189
        parent: _previousController,
        curve: Curves.easeIn,
      ),
1190 1191
    );

1192
    final CurvedAnimation currentEntranceScaleAnimation = CurvedAnimation(
1193
      parent: widget.currentController,
1194 1195
      curve: Curves.easeIn,
    );
1196
    final Animation<double> currentEntranceRotationAnimation = widget.currentController.drive(_entranceTurnTween);
1197 1198 1199 1200

    // Get the animations for when the FAB is moving.
    final Animation<double> moveScaleAnimation = widget.fabMotionAnimator.getScaleAnimation(parent: widget.fabMoveAnimation);
    final Animation<double> moveRotationAnimation = widget.fabMotionAnimator.getRotationAnimation(parent: widget.fabMoveAnimation);
1201

1202
    // Aggregate the animations.
1203 1204
    _previousScaleAnimation = AnimationMin<double>(moveScaleAnimation, previousExitScaleAnimation);
    _currentScaleAnimation = AnimationMin<double>(moveScaleAnimation, currentEntranceScaleAnimation);
1205
    _extendedCurrentScaleAnimation = _currentScaleAnimation.drive(CurveTween(curve: const Interval(0.0, 0.1)));
1206

1207 1208
    _previousRotationAnimation = TrainHoppingAnimation(previousExitRotationAnimation, moveRotationAnimation);
    _currentRotationAnimation = TrainHoppingAnimation(currentEntranceRotationAnimation, moveRotationAnimation);
1209 1210 1211 1212 1213 1214

    _currentScaleAnimation.addListener(_onProgressChanged);
    _previousScaleAnimation.addListener(_onProgressChanged);
  }

  void _handlePreviousAnimationStatusChanged(AnimationStatus status) {
1215 1216
    setState(() {
      if (status == AnimationStatus.dismissed) {
1217
        assert(widget.currentController.status == AnimationStatus.dismissed);
1218
        if (widget.child != null)
1219
          widget.currentController.forward();
1220 1221
      }
    });
1222 1223
  }

1224
  bool _isExtendedFloatingActionButton(Widget? widget) {
1225 1226
    return widget is FloatingActionButton
        && widget.isExtended;
1227 1228
  }

1229
  @override
1230
  Widget build(BuildContext context) {
1231
    return Stack(
1232
      alignment: Alignment.centerRight,
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
      children: <Widget>[
        if (_previousController.status != AnimationStatus.dismissed)
          if (_isExtendedFloatingActionButton(_previousChild))
            FadeTransition(
              opacity: _previousScaleAnimation,
              child: _previousChild,
            )
          else
            ScaleTransition(
              scale: _previousScaleAnimation,
              child: RotationTransition(
                turns: _previousRotationAnimation,
                child: _previousChild,
              ),
            ),
        if (_isExtendedFloatingActionButton(widget.child))
          ScaleTransition(
            scale: _extendedCurrentScaleAnimation,
            child: FadeTransition(
              opacity: _currentScaleAnimation,
              child: widget.child,
            ),
          )
        else
          ScaleTransition(
            scale: _currentScaleAnimation,
            child: RotationTransition(
              turns: _currentRotationAnimation,
              child: widget.child,
            ),
          ),
      ],
1265
    );
1266
  }
1267 1268

  void _onProgressChanged() {
1269
    _updateGeometryScale(math.max(_previousScaleAnimation.value, _currentScaleAnimation.value));
1270 1271 1272 1273 1274 1275 1276
  }

  void _updateGeometryScale(double scale) {
    widget.geometryNotifier._updateWith(
      floatingActionButtonScale: scale,
    );
  }
1277 1278
}

1279 1280
/// Implements the basic material design visual layout structure.
///
1281
/// This class provides APIs for showing drawers and bottom sheets.
1282
///
1283
/// To display a persistent bottom sheet, obtain the
1284
/// [ScaffoldState] for the current [BuildContext] via [Scaffold.of] and use the
1285
/// [ScaffoldState.showBottomSheet] function.
1286
///
1287
/// {@tool dartpad --template=stateful_widget_material}
1288 1289 1290 1291 1292
/// This example shows a [Scaffold] with a [body] and [FloatingActionButton].
/// The [body] is a [Text] placed in a [Center] in order to center the text
/// within the [Scaffold]. The [FloatingActionButton] is connected to a
/// callback that increments a counter.
///
1293
/// ![The Scaffold has a white background with a blue AppBar at the top. A blue FloatingActionButton is positioned at the bottom right corner of the Scaffold.](https://flutter.github.io/assets-for-api-docs/assets/material/scaffold.png)
1294 1295 1296 1297
///
/// ```dart
/// int _count = 0;
///
1298
/// @override
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
/// Widget build(BuildContext context) {
///   return Scaffold(
///     appBar: AppBar(
///       title: const Text('Sample Code'),
///     ),
///     body: Center(
///       child: Text('You have pressed the button $_count times.')
///     ),
///     floatingActionButton: FloatingActionButton(
///       onPressed: () => setState(() => _count++),
///       tooltip: 'Increment Counter',
///       child: const Icon(Icons.add),
///     ),
///   );
/// }
/// ```
/// {@end-tool}
///
1317
/// {@tool dartpad --template=stateful_widget_material}
1318 1319 1320 1321
/// This example shows a [Scaffold] with a blueGrey [backgroundColor], [body]
/// and [FloatingActionButton]. The [body] is a [Text] placed in a [Center] in
/// order to center the text within the [Scaffold]. The [FloatingActionButton]
/// is connected to a callback that increments a counter.
1322
///
1323
/// ![](https://flutter.github.io/assets-for-api-docs/assets/material/scaffold_background_color.png)
1324 1325 1326 1327
///
/// ```dart
/// int _count = 0;
///
1328
/// @override
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
/// Widget build(BuildContext context) {
///   return Scaffold(
///     appBar: AppBar(
///       title: const Text('Sample Code'),
///     ),
///     body: Center(
///       child: Text('You have pressed the button $_count times.')
///     ),
///     backgroundColor: Colors.blueGrey.shade200,
///     floatingActionButton: FloatingActionButton(
///       onPressed: () => setState(() => _count++),
///       tooltip: 'Increment Counter',
///       child: const Icon(Icons.add),
///     ),
///   );
/// }
/// ```
/// {@end-tool}
///
1348
/// {@tool dartpad --template=stateful_widget_material}
1349 1350
/// This example shows a [Scaffold] with an [AppBar], a [BottomAppBar] and a
/// [FloatingActionButton]. The [body] is a [Text] placed in a [Center] in order
1351
/// to center the text within the [Scaffold]. The [FloatingActionButton] is
1352 1353 1354
/// centered and docked within the [BottomAppBar] using
/// [FloatingActionButtonLocation.centerDocked]. The [FloatingActionButton] is
/// connected to a callback that increments a counter.
1355
///
1356
/// ![](https://flutter.github.io/assets-for-api-docs/assets/material/scaffold_bottom_app_bar.png)
1357
///
1358
/// ```dart
1359 1360
/// int _count = 0;
///
1361
/// @override
1362 1363 1364
/// Widget build(BuildContext context) {
///   return Scaffold(
///     appBar: AppBar(
1365
///       title: const Text('Sample Code'),
1366 1367 1368 1369 1370
///     ),
///     body: Center(
///       child: Text('You have pressed the button $_count times.'),
///     ),
///     bottomNavigationBar: BottomAppBar(
1371
///       shape: const CircularNotchedRectangle(),
1372
///       child: Container(height: 50.0),
1373 1374 1375 1376 1377 1378
///     ),
///     floatingActionButton: FloatingActionButton(
///       onPressed: () => setState(() {
///         _count++;
///       }),
///       tooltip: 'Increment Counter',
1379
///       child: const Icon(Icons.add),
1380 1381 1382 1383
///     ),
///     floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
///   );
/// }
1384
/// ```
1385
/// {@end-tool}
1386
///
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
/// ## Scaffold layout, the keyboard, and display "notches"
///
/// The scaffold will expand to fill the available space. That usually
/// means that it will occupy its entire window or device screen. When
/// the device's keyboard appears the Scaffold's ancestor [MediaQuery]
/// widget's [MediaQueryData.viewInsets] changes and the Scaffold will
/// be rebuilt. By default the scaffold's [body] is resized to make
/// room for the keyboard. To prevent the resize set
/// [resizeToAvoidBottomInset] to false. In either case the focused
/// widget will be scrolled into view if it's within a scrollable
/// container.
///
/// The [MediaQueryData.padding] value defines areas that might
/// not be completely visible, like the display "notch" on the iPhone
/// X. The scaffold's [body] is not inset by this padding value
/// although an [appBar] or [bottomNavigationBar] will typically
/// cause the body to avoid the padding. The [SafeArea]
/// widget can be used within the scaffold's body to avoid areas
/// like display notches.
///
/// ## Troubleshooting
///
/// ### Nested Scaffolds
///
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
/// The Scaffold is designed to be a top level container for
/// a [MaterialApp]. This means that adding a Scaffold
/// to each route on a Material app will provide the app with
/// Material's basic visual layout structure.
///
/// It is typically not necessary to nest Scaffolds. For example, in a
/// tabbed UI, where the [bottomNavigationBar] is a [TabBar]
/// and the body is a [TabBarView], you might be tempted to make each tab bar
/// view a scaffold with a differently titled AppBar. Rather, it would be
/// better to add a listener to the [TabController] that updates the
/// AppBar
1422
///
1423
/// {@tool snippet}
1424 1425 1426 1427
/// Add a listener to the app's tab controller so that the [AppBar] title of the
/// app's one and only scaffold is reset each time a new tab is selected.
///
/// ```dart
1428
/// TabController(vsync: tickerProvider, length: tabCount)..addListener(() {
1429 1430 1431 1432 1433 1434
///   if (!tabController.indexIsChanging) {
///     setState(() {
///       // Rebuild the enclosing scaffold with a new AppBar title
///       appBarTitle = 'Tab ${tabController.index}';
///     });
///   }
1435
/// })
1436
/// ```
1437
/// {@end-tool}
1438 1439 1440 1441 1442
///
/// Although there are some use cases, like a presentation app that
/// shows embedded flutter content, where nested scaffolds are
/// appropriate, it's best to avoid nesting scaffolds.
///
1443 1444
/// See also:
///
1445 1446
///  * [AppBar], which is a horizontal bar typically shown at the top of an app
///    using the [appBar] property.
1447 1448
///  * [BottomAppBar], which is a horizontal bar typically shown at the bottom
///    of an app using the [bottomNavigationBar] property.
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
///  * [FloatingActionButton], which is a circular button typically shown in the
///    bottom right corner of the app using the [floatingActionButton] property.
///  * [Drawer], which is a vertical panel that is typically displayed to the
///    left of the body (and often hidden on phones) using the [drawer]
///    property.
///  * [BottomNavigationBar], which is a horizontal array of buttons typically
///    shown along the bottom of the app using the [bottomNavigationBar]
///    property.
///  * [BottomSheet], which is an overlay typically shown near the bottom of the
///    app. A bottom sheet can either be persistent, in which case it is shown
///    using the [ScaffoldState.showBottomSheet] method, or modal, in which case
///    it is shown using the [showModalBottomSheet] function.
///  * [ScaffoldState], which is the state associated with this widget.
1462
///  * <https://material.io/design/layout/responsive-layout-grid.html>
1463
///  * Cookbook: [Add a Drawer to a screen](https://flutter.dev/docs/cookbook/design/drawer)
1464
class Scaffold extends StatefulWidget {
1465
  /// Creates a visual scaffold for material design widgets.
1466
  const Scaffold({
1467
    Key? key,
1468
    this.appBar,
Hixie's avatar
Hixie committed
1469
    this.body,
1470
    this.floatingActionButton,
1471 1472
    this.floatingActionButtonLocation,
    this.floatingActionButtonAnimator,
1473
    this.persistentFooterButtons,
1474
    this.drawer,
1475
    this.onDrawerChanged,
1476
    this.endDrawer,
1477
    this.onEndDrawerChanged,
1478
    this.bottomNavigationBar,
1479
    this.bottomSheet,
1480
    this.backgroundColor,
1481
    this.resizeToAvoidBottomInset,
1482
    this.primary = true,
1483
    this.drawerDragStartBehavior = DragStartBehavior.start,
1484
    this.extendBody = false,
1485
    this.extendBodyBehindAppBar = false,
1486
    this.drawerScrimColor,
1487
    this.drawerEdgeDragWidth,
1488 1489
    this.drawerEnableOpenDragGesture = true,
    this.endDrawerEnableOpenDragGesture = true,
1490
    this.restorationId,
1491
  }) : assert(primary != null),
1492
       assert(extendBody != null),
1493
       assert(extendBodyBehindAppBar != null),
1494 1495
       assert(drawerDragStartBehavior != null),
       super(key: key);
Adam Barth's avatar
Adam Barth committed
1496

1497 1498 1499 1500 1501
  /// If true, and [bottomNavigationBar] or [persistentFooterButtons]
  /// is specified, then the [body] extends to the bottom of the Scaffold,
  /// instead of only extending to the top of the [bottomNavigationBar]
  /// or the [persistentFooterButtons].
  ///
Pierre-Louis's avatar
Pierre-Louis committed
1502 1503
  /// If true, a [MediaQuery] widget whose bottom padding matches the height
  /// of the [bottomNavigationBar] will be added above the scaffold's [body].
1504 1505 1506 1507
  ///
  /// This property is often useful when the [bottomNavigationBar] has
  /// a non-rectangular shape, like [CircularNotchedRectangle], which
  /// adds a [FloatingActionButton] sized notch to the top edge of the bar.
nt4f04uNd's avatar
nt4f04uNd committed
1508
  /// In this case specifying `extendBody: true` ensures that scaffold's
1509
  /// body will be visible through the bottom navigation bar's notch.
1510 1511 1512 1513 1514
  ///
  /// See also:
  ///
  ///  * [extendBodyBehindAppBar], which extends the height of the body
  ///    to the top of the scaffold.
1515 1516
  final bool extendBody;

1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
  /// If true, and an [appBar] is specified, then the height of the [body] is
  /// extended to include the height of the app bar and the top of the body
  /// is aligned with the top of the app bar.
  ///
  /// This is useful if the app bar's [AppBar.backgroundColor] is not
  /// completely opaque.
  ///
  /// This property is false by default. It must not be null.
  ///
  /// See also:
  ///
  ///  * [extendBody], which extends the height of the body to the bottom
  ///    of the scaffold.
  final bool extendBodyBehindAppBar;

1532
  /// An app bar to display at the top of the scaffold.
1533
  final PreferredSizeWidget? appBar;
1534 1535 1536

  /// The primary content of the scaffold.
  ///
1537 1538 1539 1540 1541
  /// Displayed below the [appBar], above the bottom of the ambient
  /// [MediaQuery]'s [MediaQueryData.viewInsets], and behind the
  /// [floatingActionButton] and [drawer]. If [resizeToAvoidBottomInset] is
  /// false then the body is not resized when the onscreen keyboard appears,
  /// i.e. it is not inset by `viewInsets.bottom`.
1542
  ///
1543 1544 1545
  /// The widget in the body of the scaffold is positioned at the top-left of
  /// the available space between the app bar and the bottom of the scaffold. To
  /// center this widget instead, consider putting it in a [Center] widget and
1546 1547
  /// having that be the body. To expand this widget instead, consider
  /// putting it in a [SizedBox.expand].
1548 1549 1550
  ///
  /// If you have a column of widgets that should normally fit on the screen,
  /// but may overflow and would in such cases need to scroll, consider using a
1551
  /// [ListView] as the body of the scaffold. This is also a good choice for
1552
  /// the case where your body is a scrollable list.
1553
  final Widget? body;
1554

1555
  /// A button displayed floating above [body], in the bottom right corner.
1556 1557
  ///
  /// Typically a [FloatingActionButton].
1558
  final Widget? floatingActionButton;
1559

1560
  /// Responsible for determining where the [floatingActionButton] should go.
1561
  ///
1562
  /// If null, the [ScaffoldState] will use the default location, [FloatingActionButtonLocation.endFloat].
1563
  final FloatingActionButtonLocation? floatingActionButtonLocation;
1564 1565

  /// Animator to move the [floatingActionButton] to a new [floatingActionButtonLocation].
1566
  ///
1567
  /// If null, the [ScaffoldState] will use the default animator, [FloatingActionButtonAnimator.scaling].
1568
  final FloatingActionButtonAnimator? floatingActionButtonAnimator;
1569

1570 1571
  /// A set of buttons that are displayed at the bottom of the scaffold.
  ///
1572
  /// Typically this is a list of [TextButton] widgets. These buttons are
Ian Hickson's avatar
Ian Hickson committed
1573
  /// persistently visible, even if the [body] of the scaffold scrolls.
1574
  ///
1575
  /// These widgets will be wrapped in an [OverflowBar].
1576
  ///
Ian Hickson's avatar
Ian Hickson committed
1577 1578
  /// The [persistentFooterButtons] are rendered above the
  /// [bottomNavigationBar] but below the [body].
1579
  final List<Widget>? persistentFooterButtons;
1580

1581
  /// A panel displayed to the side of the [body], often hidden on mobile
1582 1583
  /// devices. Swipes in from either left-to-right ([TextDirection.ltr]) or
  /// right-to-left ([TextDirection.rtl])
1584
  ///
1585
  /// Typically a [Drawer].
1586
  ///
1587
  /// To open the drawer, use the [ScaffoldState.openDrawer] function.
1588
  ///
1589 1590
  /// To close the drawer, use [Navigator.pop].
  ///
1591
  /// {@tool dartpad --template=stateful_widget_material}
1592 1593 1594 1595
  /// To disable the drawer edge swipe, set the
  /// [Scaffold.drawerEnableOpenDragGesture] to false. Then, use
  /// [ScaffoldState.openDrawer] to open the drawer and [Navigator.pop] to close
  /// it.
1596 1597 1598 1599 1600
  ///
  /// ```dart
  /// final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  ///
  /// void _openDrawer() {
1601
  ///   _scaffoldKey.currentState!.openDrawer();
1602 1603
  /// }
  ///
1604 1605 1606 1607
  /// void _closeDrawer() {
  ///   Navigator.of(context).pop();
  /// }
  ///
1608 1609 1610 1611
  /// @override
  /// Widget build(BuildContext context) {
  ///   return Scaffold(
  ///     key: _scaffoldKey,
1612
  ///     appBar: AppBar(title: const Text('Drawer Demo')),
1613
  ///     body: Center(
1614
  ///       child: ElevatedButton(
1615
  ///         onPressed: _openDrawer,
1616
  ///         child: const Text('Open Drawer'),
1617 1618 1619
  ///       ),
  ///     ),
  ///     drawer: Drawer(
1620 1621 1622 1623 1624
  ///       child: Center(
  ///         child: Column(
  ///           mainAxisAlignment: MainAxisAlignment.center,
  ///           children: <Widget>[
  ///             const Text('This is the Drawer'),
1625
  ///             ElevatedButton(
1626 1627 1628 1629 1630 1631
  ///               onPressed: _closeDrawer,
  ///               child: const Text('Close Drawer'),
  ///             ),
  ///           ],
  ///         ),
  ///       ),
1632
  ///     ),
1633 1634
  ///     // Disable opening the drawer with a swipe gesture.
  ///     drawerEnableOpenDragGesture: false,
1635 1636 1637 1638
  ///   );
  /// }
  /// ```
  /// {@end-tool}
1639
  final Widget? drawer;
1640

1641 1642 1643
  /// Optional callback that is called when the [Scaffold.drawer] is opened or closed.
  final DrawerCallback? onDrawerChanged;

1644 1645 1646 1647 1648
  /// A panel displayed to the side of the [body], often hidden on mobile
  /// devices. Swipes in from right-to-left ([TextDirection.ltr]) or
  /// left-to-right ([TextDirection.rtl])
  ///
  /// Typically a [Drawer].
1649
  ///
1650
  /// To open the drawer, use the [ScaffoldState.openEndDrawer] function.
1651
  ///
1652 1653
  /// To close the drawer, use [Navigator.pop].
  ///
1654
  /// {@tool dartpad --template=stateful_widget_material}
1655 1656 1657 1658
  /// To disable the drawer edge swipe, set the
  /// [Scaffold.endDrawerEnableOpenDragGesture] to false. Then, use
  /// [ScaffoldState.openEndDrawer] to open the drawer and [Navigator.pop] to
  /// close it.
1659 1660 1661 1662 1663
  ///
  /// ```dart
  /// final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  ///
  /// void _openEndDrawer() {
1664
  ///   _scaffoldKey.currentState!.openEndDrawer();
1665 1666
  /// }
  ///
1667 1668 1669 1670
  /// void _closeEndDrawer() {
  ///   Navigator.of(context).pop();
  /// }
  ///
1671 1672 1673 1674
  /// @override
  /// Widget build(BuildContext context) {
  ///   return Scaffold(
  ///     key: _scaffoldKey,
1675
  ///     appBar: AppBar(title: const Text('Drawer Demo')),
1676
  ///     body: Center(
1677
  ///       child: ElevatedButton(
1678
  ///         onPressed: _openEndDrawer,
1679
  ///         child: const Text('Open End Drawer'),
1680 1681 1682
  ///       ),
  ///     ),
  ///     endDrawer: Drawer(
1683 1684 1685 1686 1687
  ///       child: Center(
  ///         child: Column(
  ///           mainAxisAlignment: MainAxisAlignment.center,
  ///           children: <Widget>[
  ///             const Text('This is the Drawer'),
1688
  ///             ElevatedButton(
1689 1690 1691 1692 1693 1694
  ///               onPressed: _closeEndDrawer,
  ///               child: const Text('Close Drawer'),
  ///             ),
  ///           ],
  ///         ),
  ///       ),
1695
  ///     ),
1696 1697
  ///     // Disable opening the end drawer with a swipe gesture.
  ///     endDrawerEnableOpenDragGesture: false,
1698 1699 1700 1701
  ///   );
  /// }
  /// ```
  /// {@end-tool}
1702
  final Widget? endDrawer;
1703

1704 1705 1706
  /// Optional callback that is called when the [Scaffold.endDrawer] is opened or closed.
  final DrawerCallback? onEndDrawerChanged;

1707 1708 1709
  /// The color to use for the scrim that obscures primary content while a drawer is open.
  ///
  /// By default, the color is [Colors.black54]
1710
  final Color? drawerScrimColor;
1711

1712 1713 1714
  /// The color of the [Material] widget that underlies the entire Scaffold.
  ///
  /// The theme's [ThemeData.scaffoldBackgroundColor] by default.
1715
  final Color? backgroundColor;
1716

1717 1718
  /// A bottom navigation bar to display at the bottom of the scaffold.
  ///
1719 1720
  /// Snack bars slide from underneath the bottom navigation bar while bottom
  /// sheets are stacked on top.
Ian Hickson's avatar
Ian Hickson committed
1721 1722 1723
  ///
  /// The [bottomNavigationBar] is rendered below the [persistentFooterButtons]
  /// and the [body].
1724
  final Widget? bottomNavigationBar;
1725

1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
  /// The persistent bottom sheet to display.
  ///
  /// A persistent bottom sheet shows information that supplements the primary
  /// content of the app. A persistent bottom sheet remains visible even when
  /// the user interacts with other parts of the app.
  ///
  /// A closely related widget is a modal bottom sheet, which is an alternative
  /// to a menu or a dialog and prevents the user from interacting with the rest
  /// of the app. Modal bottom sheets can be created and displayed with the
  /// [showModalBottomSheet] function.
  ///
  /// Unlike the persistent bottom sheet displayed by [showBottomSheet]
  /// this bottom sheet is not a [LocalHistoryEntry] and cannot be dismissed
  /// with the scaffold appbar's back button.
  ///
  /// If a persistent bottom sheet created with [showBottomSheet] is already
  /// visible, it must be closed before building the Scaffold with a new
  /// [bottomSheet].
  ///
  /// The value of [bottomSheet] can be any widget at all. It's unlikely to
  /// actually be a [BottomSheet], which is used by the implementations of
  /// [showBottomSheet] and [showModalBottomSheet]. Typically it's a widget
  /// that includes [Material].
  ///
  /// See also:
  ///
  ///  * [showBottomSheet], which displays a bottom sheet as a route that can
  ///    be dismissed with the scaffold's back button.
  ///  * [showModalBottomSheet], which displays a modal bottom sheet.
1755
  final Widget? bottomSheet;
1756

1757 1758 1759
  /// If true the [body] and the scaffold's floating widgets should size
  /// themselves to avoid the onscreen keyboard whose height is defined by the
  /// ambient [MediaQuery]'s [MediaQueryData.viewInsets] `bottom` property.
1760 1761 1762 1763 1764 1765
  ///
  /// For example, if there is an onscreen keyboard displayed above the
  /// scaffold, the body can be resized to avoid overlapping the keyboard, which
  /// prevents widgets inside the body from being obscured by the keyboard.
  ///
  /// Defaults to true.
1766
  final bool? resizeToAvoidBottomInset;
1767

1768 1769 1770 1771 1772 1773 1774 1775 1776
  /// Whether this scaffold is being displayed at the top of the screen.
  ///
  /// If true then the height of the [appBar] will be extended by the height
  /// of the screen's status bar, i.e. the top padding for [MediaQuery].
  ///
  /// The default value of this property, like the default value of
  /// [AppBar.primary], is true.
  final bool primary;

1777
  /// {@macro flutter.material.DrawerController.dragStartBehavior}
1778 1779
  final DragStartBehavior drawerDragStartBehavior;

1780 1781 1782 1783
  /// The width of the area within which a horizontal swipe will open the
  /// drawer.
  ///
  /// By default, the value used is 20.0 added to the padding edge of
1784 1785 1786 1787 1788
  /// `MediaQuery.of(context).padding` that corresponds to the surrounding
  /// [TextDirection]. This ensures that the drag area for notched devices is
  /// not obscured. For example, if `TextDirection.of(context)` is set to
  /// [TextDirection.ltr], 20.0 will be added to
  /// `MediaQuery.of(context).padding.left`.
1789
  final double? drawerEdgeDragWidth;
1790

1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
  /// Determines if the [Scaffold.drawer] can be opened with a drag
  /// gesture.
  ///
  /// By default, the drag gesture is enabled.
  final bool drawerEnableOpenDragGesture;

  /// Determines if the [Scaffold.endDrawer] can be opened with a
  /// drag gesture.
  ///
  /// By default, the drag gesture is enabled.
  final bool endDrawerEnableOpenDragGesture;

1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
  /// Restoration ID to save and restore the state of the [Scaffold].
  ///
  /// If it is non-null, the scaffold will persist and restore whether the
  /// [drawer] and [endDrawer] was open or closed.
  ///
  /// The state of this widget is persisted in a [RestorationBucket] claimed
  /// from the surrounding [RestorationScope] using the provided restoration ID.
  ///
  /// See also:
  ///
  ///  * [RestorationManager], which explains how state restoration works in
  ///    Flutter.
  final String? restorationId;

1817 1818 1819 1820 1821
  /// Finds the [ScaffoldState] from the closest instance of this class that
  /// encloses the given context.
  ///
  /// If no instance of this class encloses the given context, will cause an
  /// assert in debug mode, and throw an exception in release mode.
1822
  ///
1823 1824
  /// This method can be expensive (it walks the element tree).
  ///
1825
  /// {@tool dartpad --template=freeform}
1826 1827 1828 1829 1830 1831 1832 1833
  /// Typical usage of the [Scaffold.of] function is to call it from within the
  /// `build` method of a child of a [Scaffold].
  ///
  /// ```dart imports
  /// import 'package:flutter/material.dart';
  /// ```
  ///
  /// ```dart main
1834
  /// void main() => runApp(const MyApp());
1835 1836 1837 1838
  /// ```
  ///
  /// ```dart preamble
  /// class MyApp extends StatelessWidget {
1839 1840
  ///   const MyApp({Key? key}) : super(key: key);
  ///
1841 1842 1843 1844 1845 1846 1847 1848 1849
  ///   // This widget is the root of your application.
  ///   @override
  ///   Widget build(BuildContext context) {
  ///     return MaterialApp(
  ///       title: 'Flutter Code Sample for Scaffold.of.',
  ///       theme: ThemeData(
  ///         primarySwatch: Colors.blue,
  ///       ),
  ///       home: Scaffold(
1850
  ///         body: const MyScaffoldBody(),
1851
  ///         appBar: AppBar(title: const Text('Scaffold.of Example')),
1852 1853 1854 1855 1856 1857
  ///       ),
  ///       color: Colors.white,
  ///     );
  ///   }
  /// }
  /// ```
1858 1859
  ///
  /// ```dart
1860
  /// class MyScaffoldBody extends StatelessWidget {
1861 1862
  ///   const MyScaffoldBody({Key? key}) : super(key: key);
  ///
1863 1864 1865
  ///   @override
  ///   Widget build(BuildContext context) {
  ///     return Center(
1866
  ///       child: ElevatedButton(
1867
  ///         child: const Text('SHOW BOTTOM SHEET'),
1868
  ///         onPressed: () {
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
  ///           Scaffold.of(context).showBottomSheet<void>(
  ///             (BuildContext context) {
  ///               return Container(
  ///                 alignment: Alignment.center,
  ///                 height: 200,
  ///                 color: Colors.amber,
  ///                 child: Center(
  ///                   child: Column(
  ///                     mainAxisSize: MainAxisSize.min,
  ///                     children: <Widget>[
  ///                       const Text('BottomSheet'),
  ///                       ElevatedButton(
  ///                         child: const Text('Close BottomSheet'),
  ///                         onPressed: () {
  ///                           Navigator.pop(context);
  ///                         },
  ///                       )
  ///                     ],
  ///                   ),
  ///                 ),
  ///               );
  ///             },
1891 1892 1893 1894 1895
  ///           );
  ///         },
  ///       ),
  ///     );
  ///   }
1896 1897
  /// }
  /// ```
1898
  /// {@end-tool}
1899
  ///
1900
  /// {@tool dartpad --template=stateless_widget_material}
1901 1902
  /// When the [Scaffold] is actually created in the same `build` function, the
  /// `context` argument to the `build` function can't be used to find the
1903 1904 1905 1906
  /// [Scaffold] (since it's "above" the widget being returned in the widget
  /// tree). In such cases, the following technique with a [Builder] can be used
  /// to provide a new scope with a [BuildContext] that is "under" the
  /// [Scaffold]:
1907 1908 1909
  ///
  /// ```dart
  /// Widget build(BuildContext context) {
1910
  ///   return Scaffold(
1911
  ///     appBar: AppBar(title: const Text('Demo')),
1912
  ///     body: Builder(
1913 1914 1915
  ///       // Create an inner BuildContext so that the onPressed methods
  ///       // can refer to the Scaffold with Scaffold.of().
  ///       builder: (BuildContext context) {
1916
  ///         return Center(
1917
  ///           child: ElevatedButton(
1918
  ///             child: const Text('SHOW BOTTOM SHEET'),
1919
  ///             onPressed: () {
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942
  ///               Scaffold.of(context).showBottomSheet<void>(
  ///                 (BuildContext context) {
  ///                   return Container(
  ///                     alignment: Alignment.center,
  ///                     height: 200,
  ///                     color: Colors.amber,
  ///                     child: Center(
  ///                       child: Column(
  ///                         mainAxisSize: MainAxisSize.min,
  ///                         children: <Widget>[
  ///                           const Text('BottomSheet'),
  ///                           ElevatedButton(
  ///                             child: const Text('Close BottomSheet'),
  ///                             onPressed: () {
  ///                               Navigator.pop(context);
  ///                             },
  ///                           )
  ///                         ],
  ///                       ),
  ///                     ),
  ///                   );
  ///                 },
  ///               );
1943 1944 1945 1946 1947 1948 1949 1950
  ///             },
  ///           ),
  ///         );
  ///       },
  ///     ),
  ///   );
  /// }
  /// ```
1951
  /// {@end-tool}
1952
  ///
1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
  /// A more efficient solution is to split your build function into several
  /// widgets. This introduces a new context from which you can obtain the
  /// [Scaffold]. In this solution, you would have an outer widget that creates
  /// the [Scaffold] populated by instances of your new inner widgets, and then
  /// in these inner widgets you would use [Scaffold.of].
  ///
  /// A less elegant but more expedient solution is assign a [GlobalKey] to the
  /// [Scaffold], then use the `key.currentState` property to obtain the
  /// [ScaffoldState] rather than using the [Scaffold.of] function.
  ///
1963
  /// If there is no [Scaffold] in scope, then this will throw an exception.
1964 1965
  /// To return null if there is no [Scaffold], use [maybeOf] instead.
  static ScaffoldState of(BuildContext context) {
1966
    assert(context != null);
1967
    final ScaffoldState? result = context.findAncestorStateOfType<ScaffoldState>();
1968
    if (result != null)
1969
      return result;
1970 1971
    throw FlutterError.fromParts(<DiagnosticsNode>[
      ErrorSummary(
1972
        'Scaffold.of() called with a context that does not contain a Scaffold.',
1973 1974 1975 1976
      ),
      ErrorDescription(
        'No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). '
        'This usually happens when the context provided is from the same StatefulWidget as that '
1977
        'whose build function actually creates the Scaffold widget being sought.',
1978 1979 1980 1981 1982
      ),
      ErrorHint(
        'There are several ways to avoid this problem. The simplest is to use a Builder to get a '
        'context that is "under" the Scaffold. For an example of this, please see the '
        'documentation for Scaffold.of():\n'
1983
        '  https://api.flutter.dev/flutter/material/Scaffold/of.html',
1984 1985 1986 1987 1988 1989 1990 1991
      ),
      ErrorHint(
        'A more efficient solution is to split your build function into several widgets. This '
        'introduces a new context from which you can obtain the Scaffold. In this solution, '
        'you would have an outer widget that creates the Scaffold populated by instances of '
        'your new inner widgets, and then in these inner widgets you would use Scaffold.of().\n'
        'A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, '
        'then use the key.currentState property to obtain the ScaffoldState rather than '
1992
        'using the Scaffold.of() function.',
1993
      ),
1994
      context.describeElement('The context used was'),
1995
    ]);
1996
  }
Hixie's avatar
Hixie committed
1997

1998 1999 2000 2001 2002 2003
  /// Finds the [ScaffoldState] from the closest instance of this class that
  /// encloses the given context.
  ///
  /// If no instance of this class encloses the given context, will return null.
  /// To throw an exception instead, use [of] instead of this function.
  ///
2004 2005
  /// This method can be expensive (it walks the element tree).
  ///
2006 2007 2008 2009 2010 2011 2012 2013 2014 2015
  /// See also:
  ///
  ///  * [of], a similar function to this one that throws if no instance
  ///    encloses the given context. Also includes some sample code in its
  ///    documentation.
  static ScaffoldState? maybeOf(BuildContext context) {
    assert(context != null);
    return context.findAncestorStateOfType<ScaffoldState>();
  }

2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
  /// Returns a [ValueListenable] for the [ScaffoldGeometry] for the closest
  /// [Scaffold] ancestor of the given context.
  ///
  /// The [ValueListenable.value] is only available at paint time.
  ///
  /// Notifications are guaranteed to be sent before the first paint pass
  /// with the new geometry, but there is no guarantee whether a build or
  /// layout passes are going to happen between the notification and the next
  /// paint pass.
  ///
  /// The closest [Scaffold] ancestor for the context might change, e.g when
  /// an element is moved from one scaffold to another. For [StatefulWidget]s
  /// using this listenable, a change of the [Scaffold] ancestor will
  /// trigger a [State.didChangeDependencies].
  ///
  /// A typical pattern for listening to the scaffold geometry would be to
  /// call [Scaffold.geometryOf] in [State.didChangeDependencies], compare the
  /// return value with the previous listenable, if it has changed, unregister
  /// the listener, and register a listener to the new [ScaffoldGeometry]
  /// listenable.
2036
  static ValueListenable<ScaffoldGeometry> geometryOf(BuildContext context) {
2037
    final _ScaffoldScope? scaffoldScope = context.dependOnInheritedWidgetOfExactType<_ScaffoldScope>();
2038
    if (scaffoldScope == null)
2039 2040
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary(
2041
          'Scaffold.geometryOf() called with a context that does not contain a Scaffold.',
2042 2043 2044
        ),
        ErrorDescription(
          'This usually happens when the context provided is from the same StatefulWidget as that '
2045
          'whose build function actually creates the Scaffold widget being sought.',
2046 2047 2048 2049 2050
        ),
        ErrorHint(
          'There are several ways to avoid this problem. The simplest is to use a Builder to get a '
          'context that is "under" the Scaffold. For an example of this, please see the '
          'documentation for Scaffold.of():\n'
2051
          '  https://api.flutter.dev/flutter/material/Scaffold/of.html',
2052 2053 2054 2055 2056 2057 2058
        ),
        ErrorHint(
          'A more efficient solution is to split your build function into several widgets. This '
          'introduces a new context from which you can obtain the Scaffold. In this solution, '
          'you would have an outer widget that creates the Scaffold populated by instances of '
          'your new inner widgets, and then in these inner widgets you would use Scaffold.geometryOf().',
        ),
2059
        context.describeElement('The context used was'),
2060
      ]);
2061 2062 2063
    return scaffoldScope.geometryNotifier;
  }

2064 2065 2066 2067 2068 2069 2070 2071 2072
  /// Whether the Scaffold that most tightly encloses the given context has a
  /// drawer.
  ///
  /// If this is being used during a build (for example to decide whether to
  /// show an "open drawer" button), set the `registerForUpdates` argument to
  /// true. This will then set up an [InheritedWidget] relationship with the
  /// [Scaffold] so that the client widget gets rebuilt whenever the [hasDrawer]
  /// value changes.
  ///
2073 2074
  /// This method can be expensive (it walks the element tree).
  ///
2075
  /// See also:
2076
  ///
2077
  ///  * [Scaffold.of], which provides access to the [ScaffoldState] object as a
2078
  ///    whole, from which you can show bottom sheets, and so forth.
2079
  static bool hasDrawer(BuildContext context, { bool registerForUpdates = true }) {
2080 2081 2082
    assert(registerForUpdates != null);
    assert(context != null);
    if (registerForUpdates) {
2083
      final _ScaffoldScope? scaffold = context.dependOnInheritedWidgetOfExactType<_ScaffoldScope>();
2084 2085
      return scaffold?.hasDrawer ?? false;
    } else {
2086
      final ScaffoldState? scaffold = context.findAncestorStateOfType<ScaffoldState>();
2087 2088 2089 2090
      return scaffold?.hasDrawer ?? false;
    }
  }

2091
  @override
2092
  ScaffoldState createState() => ScaffoldState();
Hixie's avatar
Hixie committed
2093 2094
}

2095 2096
/// State for a [Scaffold].
///
2097 2098
/// Can display [BottomSheet]s. Retrieve a [ScaffoldState] from the current
/// [BuildContext] using [Scaffold.of].
2099 2100 2101 2102 2103 2104 2105 2106 2107
class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin, RestorationMixin {
  @override
  String? get restorationId => widget.restorationId;

  @override
  void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
    registerForRestoration(_drawerOpened, 'drawer_open');
    registerForRestoration(_endDrawerOpened, 'end_drawer_open');
  }
Hixie's avatar
Hixie committed
2108

2109 2110
  // DRAWER API

2111 2112
  final GlobalKey<DrawerControllerState> _drawerKey = GlobalKey<DrawerControllerState>();
  final GlobalKey<DrawerControllerState> _endDrawerKey = GlobalKey<DrawerControllerState>();
2113

2114 2115
  /// Whether this scaffold has a non-null [Scaffold.appBar].
  bool get hasAppBar => widget.appBar != null;
2116
  /// Whether this scaffold has a non-null [Scaffold.drawer].
2117
  bool get hasDrawer => widget.drawer != null;
2118 2119
  /// Whether this scaffold has a non-null [Scaffold.endDrawer].
  bool get hasEndDrawer => widget.endDrawer != null;
2120 2121
  /// Whether this scaffold has a non-null [Scaffold.floatingActionButton].
  bool get hasFloatingActionButton => widget.floatingActionButton != null;
2122

2123
  double? _appBarMaxHeight;
2124 2125 2126
  /// The max height the [Scaffold.appBar] uses.
  ///
  /// This is based on the appBar preferred height plus the top padding.
2127
  double? get appBarMaxHeight => _appBarMaxHeight;
2128 2129
  final RestorableBool _drawerOpened = RestorableBool(false);
  final RestorableBool _endDrawerOpened = RestorableBool(false);
jslavitz's avatar
jslavitz committed
2130

2131 2132 2133 2134
  /// Whether the [Scaffold.drawer] is opened.
  ///
  /// See also:
  ///
2135 2136
  ///  * [ScaffoldState.openDrawer], which opens the [Scaffold.drawer] of a
  ///    [Scaffold].
2137
  bool get isDrawerOpen => _drawerOpened.value;
2138 2139 2140 2141 2142

  /// Whether the [Scaffold.endDrawer] is opened.
  ///
  /// See also:
  ///
2143 2144
  ///  * [ScaffoldState.openEndDrawer], which opens the [Scaffold.endDrawer] of
  ///    a [Scaffold].
2145
  bool get isEndDrawerOpen => _endDrawerOpened.value;
2146

jslavitz's avatar
jslavitz committed
2147 2148
  void _drawerOpenedCallback(bool isOpened) {
    setState(() {
2149
      _drawerOpened.value = isOpened;
jslavitz's avatar
jslavitz committed
2150
    });
2151
    widget.onDrawerChanged?.call(isOpened);
jslavitz's avatar
jslavitz committed
2152 2153 2154 2155
  }

  void _endDrawerOpenedCallback(bool isOpened) {
    setState(() {
2156
      _endDrawerOpened.value = isOpened;
jslavitz's avatar
jslavitz committed
2157
    });
2158
    widget.onEndDrawerChanged?.call(isOpened);
jslavitz's avatar
jslavitz committed
2159 2160
  }

2161 2162 2163 2164
  /// Opens the [Drawer] (if any).
  ///
  /// If the scaffold has a non-null [Scaffold.drawer], this function will cause
  /// the drawer to begin its entrance animation.
2165 2166 2167 2168 2169 2170
  ///
  /// Normally this is not needed since the [Scaffold] automatically shows an
  /// appropriate [IconButton], and handles the edge-swipe gesture, to show the
  /// drawer.
  ///
  /// To close the drawer once it is open, use [Navigator.pop].
2171 2172
  ///
  /// See [Scaffold.of] for information about how to obtain the [ScaffoldState].
2173
  void openDrawer() {
2174
    if (_endDrawerKey.currentState != null && _endDrawerOpened.value)
2175
      _endDrawerKey.currentState!.close();
2176
    _drawerKey.currentState?.open();
2177 2178
  }

2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
  /// Opens the end side [Drawer] (if any).
  ///
  /// If the scaffold has a non-null [Scaffold.endDrawer], this function will cause
  /// the end side drawer to begin its entrance animation.
  ///
  /// Normally this is not needed since the [Scaffold] automatically shows an
  /// appropriate [IconButton], and handles the edge-swipe gesture, to show the
  /// drawer.
  ///
  /// To close the end side drawer once it is open, use [Navigator.pop].
  ///
  /// See [Scaffold.of] for information about how to obtain the [ScaffoldState].
  void openEndDrawer() {
2192
    if (_drawerKey.currentState != null && _drawerOpened.value)
2193
      _drawerKey.currentState!.close();
2194 2195 2196
    _endDrawerKey.currentState?.open();
  }

2197
  // SNACKBAR API
2198
  final Queue<ScaffoldFeatureController<SnackBar, SnackBarClosedReason>> _snackBars = Queue<ScaffoldFeatureController<SnackBar, SnackBarClosedReason>>();
2199 2200 2201
  AnimationController? _snackBarController;
  Timer? _snackBarTimer;
  bool? _accessibleNavigation;
2202
  ScaffoldMessengerState? _scaffoldMessenger;
Hixie's avatar
Hixie committed
2203

2204 2205 2206
  /// [ScaffoldMessengerState.showSnackBar] shows a [SnackBar] at the bottom of
  /// the scaffold. This method should not be used, and will be deprecated in
  /// the near future..
2207 2208 2209 2210 2211
  ///
  /// A scaffold can show at most one snack bar at a time. If this function is
  /// called while another snack bar is already visible, the given snack bar
  /// will be added to a queue and displayed after the earlier snack bars have
  /// closed.
2212 2213 2214
  ///
  /// To control how long a [SnackBar] remains visible, use [SnackBar.duration].
  ///
2215 2216 2217 2218 2219
  /// To remove the [SnackBar] with an exit animation, use
  /// [ScaffoldMessengerState.hideCurrentSnackBar] or call
  /// [ScaffoldFeatureController.close] on the returned [ScaffoldFeatureController].
  /// To remove a [SnackBar] suddenly (without an animation), use
  /// [ScaffoldMessengerState.removeCurrentSnackBar].
2220
  ///
2221 2222
  /// See [ScaffoldMessenger.of] for information about how to obtain the
  /// [ScaffoldMessengerState].
2223
  ///
2224
  /// {@tool dartpad --template=stateless_widget_scaffold_center}
2225 2226 2227 2228 2229
  ///
  /// Here is an example of showing a [SnackBar] when the user presses a button.
  ///
  /// ```dart
  ///   Widget build(BuildContext context) {
2230
  ///     return OutlinedButton(
2231
  ///       onPressed: () {
2232
  ///         ScaffoldMessenger.of(context).showSnackBar(
2233 2234
  ///           const SnackBar(
  ///             content: Text('A SnackBar has been shown.'),
2235 2236 2237
  ///           ),
  ///         );
  ///       },
2238
  ///       child: const Text('Show SnackBar'),
2239 2240 2241 2242
  ///     );
  ///   }
  /// ```
  /// {@end-tool}
2243 2244 2245 2246
  ///
  /// See also:
  ///
  ///   * [ScaffoldMessenger], this should be used instead to manage [SnackBar]s.
2247 2248
  @Deprecated(
    'Use ScaffoldMessenger.showSnackBar. '
2249
    'This feature was deprecated after v1.23.0-14.0.pre.',
2250
  )
2251
  ScaffoldFeatureController<SnackBar, SnackBarClosedReason> showSnackBar(SnackBar snackbar) {
2252 2253 2254
    _snackBarController ??= SnackBar.createAnimationController(vsync: this)
      ..addStatusListener(_handleSnackBarStatusChange);
    if (_snackBars.isEmpty) {
2255 2256
      assert(_snackBarController!.isDismissed);
      _snackBarController!.forward();
2257
    }
2258
    late ScaffoldFeatureController<SnackBar, SnackBarClosedReason> controller;
2259 2260 2261 2262
    controller = ScaffoldFeatureController<SnackBar, SnackBarClosedReason>._(
      // We provide a fallback key so that if back-to-back snackbars happen to
      // match in structure, material ink splashes and highlights don't survive
      // from one to the next.
2263
      snackbar.withAnimation(_snackBarController!, fallbackKey: UniqueKey()),
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
      Completer<SnackBarClosedReason>(),
      () {
        assert(_snackBars.first == controller);
        hideCurrentSnackBar(reason: SnackBarClosedReason.hide);
      },
      null, // SnackBar doesn't use a builder function so setState() wouldn't rebuild it
    );
    setState(() {
      _snackBars.addLast(controller);
    });
    return controller;
  }

  void _handleSnackBarStatusChange(AnimationStatus status) {
    switch (status) {
      case AnimationStatus.dismissed:
        assert(_snackBars.isNotEmpty);
        setState(() {
          _snackBars.removeFirst();
        });
        if (_snackBars.isNotEmpty)
2285
          _snackBarController!.forward();
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
        break;
      case AnimationStatus.completed:
        setState(() {
          assert(_snackBarTimer == null);
          // build will create a new timer if necessary to dismiss the snack bar
        });
        break;
      case AnimationStatus.forward:
      case AnimationStatus.reverse:
        break;
    }
Hixie's avatar
Hixie committed
2297 2298
  }

2299 2300
  /// [ScaffoldMessengerState.removeCurrentSnackBar] removes the current
  /// [SnackBar] (if any) immediately. This method should not be used, and will
2301
  /// be deprecated in the near future.
2302 2303 2304
  ///
  /// The removed snack bar does not run its normal exit animation. If there are
  /// any queued snack bars, they begin their entrance animation immediately.
2305 2306 2307 2308
  ///
  /// See also:
  ///
  ///   * [ScaffoldMessenger], this should be used instead to manage [SnackBar]s.
2309 2310
  @Deprecated(
    'Use ScaffoldMessenger.removeCurrentSnackBar. '
2311
    'This feature was deprecated after v1.23.0-14.0.pre.',
2312
  )
2313
  void removeCurrentSnackBar({ SnackBarClosedReason reason = SnackBarClosedReason.remove }) {
2314
    assert(reason != null);
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325

    // SnackBars and SnackBarActions can call to hide and remove themselves, but
    // they are not aware of who presented them, the Scaffold or the
    // ScaffoldMessenger. As such, when the SnackBar classes call upon Scaffold
    // to remove (the current default), we should re-direct to the
    // ScaffoldMessenger here if that is where the SnackBar originated from.
    if (_messengerSnackBar != null) {
      // ScaffoldMessenger is presenting SnackBars.
      assert(debugCheckHasScaffoldMessenger(context));
      assert(
        _scaffoldMessenger != null,
2326 2327 2328 2329
        'A SnackBar was shown by the ScaffoldMessenger, but has been called upon '
        'to be removed from a Scaffold that is not registered with a '
        'ScaffoldMessenger, this can happen if a Scaffold has been rebuilt '
        'without an ancestor ScaffoldMessenger.',
2330 2331 2332 2333 2334
      );
      _scaffoldMessenger!.removeCurrentSnackBar(reason: reason);
      return;
    }

2335 2336 2337 2338 2339 2340 2341
    if (_snackBars.isEmpty)
      return;
    final Completer<SnackBarClosedReason> completer = _snackBars.first._completer;
    if (!completer.isCompleted)
      completer.complete(reason);
    _snackBarTimer?.cancel();
    _snackBarTimer = null;
2342
    _snackBarController!.value = 0.0;
2343 2344
  }

2345 2346 2347
  /// [ScaffoldMessengerState.hideCurrentSnackBar] removes the current
  /// [SnackBar] by running its normal exit animation. This method should not be
  /// used, and will be deprecated in the near future.
2348 2349
  ///
  /// The closed completer is called after the animation is complete.
2350 2351 2352 2353
  ///
  /// See also:
  ///
  ///   * [ScaffoldMessenger], this should be used instead to manage [SnackBar]s.
2354 2355
  @Deprecated(
    'Use ScaffoldMessenger.hideCurrentSnackBar. '
2356
    'This feature was deprecated after v1.23.0-14.0.pre.',
2357
  )
2358
  void hideCurrentSnackBar({ SnackBarClosedReason reason = SnackBarClosedReason.hide }) {
2359
    assert(reason != null);
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369

    // SnackBars and SnackBarActions can call to hide and remove themselves, but
    // they are not aware of who presented them, the Scaffold or the
    // ScaffoldMessenger. As such, when the SnackBar classes call upon Scaffold
    // to remove (the current default), we should re-direct to the
    // ScaffoldMessenger here if that is where the SnackBar originated from.
    if (_messengerSnackBar != null) {
      // ScaffoldMessenger is presenting SnackBars.
      assert(debugCheckHasScaffoldMessenger(context));
      assert(
2370 2371
        _scaffoldMessenger != null,
        'A SnackBar was shown by the ScaffoldMessenger, but has been called upon '
2372 2373 2374 2375 2376 2377 2378 2379
        'to be removed from a Scaffold that is not registered with a '
        'ScaffoldMessenger, this can happen if a Scaffold has been rebuilt '
        'without an ancestor ScaffoldMessenger.',
      );
      _scaffoldMessenger!.hideCurrentSnackBar(reason: reason);
      return;
    }

2380
    if (_snackBars.isEmpty || _snackBarController!.status == AnimationStatus.dismissed)
2381
      return;
2382
    final MediaQueryData mediaQuery = MediaQuery.of(context);
2383 2384
    final Completer<SnackBarClosedReason> completer = _snackBars.first._completer;
    if (mediaQuery.accessibleNavigation) {
2385
      _snackBarController!.value = 0.0;
2386 2387
      completer.complete(reason);
    } else {
2388
      _snackBarController!.reverse().then<void>((void value) {
2389 2390 2391 2392 2393 2394 2395
        assert(mounted);
        if (!completer.isCompleted)
          completer.complete(reason);
      });
    }
    _snackBarTimer?.cancel();
    _snackBarTimer = null;
Hixie's avatar
Hixie committed
2396 2397
  }

2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
  // The _messengerSnackBar represents the current SnackBar being managed by
  // the ScaffoldMessenger, instead of the Scaffold.
  ScaffoldFeatureController<SnackBar, SnackBarClosedReason>? _messengerSnackBar;

  // This is used to update the _messengerSnackBar by the ScaffoldMessenger.
  void _updateSnackBar() {
    setState(() {
        _messengerSnackBar = _scaffoldMessenger!._snackBars.isNotEmpty
          ? _scaffoldMessenger!._snackBars.first
          : null;
    });
  }
2410

2411 2412
  // PERSISTENT BOTTOM SHEET API

2413 2414 2415 2416
  // Contains bottom sheets that may still be animating out of view.
  // Important if the app/user takes an action that could repeatedly show a
  // bottom sheet.
  final List<_StandardBottomSheet> _dismissedBottomSheets = <_StandardBottomSheet>[];
2417
  PersistentBottomSheetController<dynamic>? _currentBottomSheet;
2418
  GlobalKey _currentBottomSheetKey = GlobalKey();
2419

2420 2421
  void _maybeBuildPersistentBottomSheet() {
    if (widget.bottomSheet != null && _currentBottomSheet == null) {
2422 2423 2424
      // The new _currentBottomSheet is not a local history entry so a "back" button
      // will not be added to the Scaffold's appbar and the bottom sheet will not
      // support drag or swipe to dismiss.
2425
      final AnimationController animationController = BottomSheet.createAnimationController(this)..value = 1.0;
2426
      LocalHistoryEntry? _persistentSheetHistoryEntry;
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437
      bool _persistentBottomSheetExtentChanged(DraggableScrollableNotification notification) {
        if (notification.extent > notification.initialExtent) {
          if (_persistentSheetHistoryEntry == null) {
            _persistentSheetHistoryEntry = LocalHistoryEntry(onRemove: () {
              if (notification.extent > notification.initialExtent) {
                DraggableScrollableActuator.reset(notification.context);
              }
              showBodyScrim(false, 0.0);
              _floatingActionButtonVisibilityValue = 1.0;
              _persistentSheetHistoryEntry = null;
            });
2438
            ModalRoute.of(context)!.addLocalHistoryEntry(_persistentSheetHistoryEntry!);
2439 2440
          }
        } else if (_persistentSheetHistoryEntry != null) {
2441
          ModalRoute.of(context)!.removeLocalHistoryEntry(_persistentSheetHistoryEntry!);
2442 2443 2444 2445
        }
        return false;
      }

2446 2447 2448 2449 2450
      // It is possible that the fade-out animation of the sheet has not finished
      // yet, and the key needs to be regenerated at this time, otherwise, there will
      // be an exception of duplicate GlobalKey.
      if (_currentBottomSheetKey.currentState != null)
        _currentBottomSheetKey = GlobalKey();
2451
      _currentBottomSheet = _buildBottomSheet<void>(
2452
        (BuildContext context) {
2453
          assert(_currentBottomSheetKey.currentState == null);
2454 2455 2456
          return NotificationListener<DraggableScrollableNotification>(
            onNotification: _persistentBottomSheetExtentChanged,
            child: DraggableScrollableActuator(
2457 2458 2459 2460
              child: StatefulBuilder(
                key: _currentBottomSheetKey,
                builder: (BuildContext context, StateSetter setState) => widget.bottomSheet!,
              ),
2461 2462 2463 2464 2465
            ),
          );
        },
        true,
        animationController: animationController,
2466 2467 2468 2469 2470
      );
    }
  }

  void _closeCurrentBottomSheet() {
2471
    if (_currentBottomSheet != null) {
2472 2473
      if (!_currentBottomSheet!._isLocalHistoryEntry) {
        _currentBottomSheet!.close();
2474 2475
      }
      assert(() {
2476
        _currentBottomSheet?._completer.future.whenComplete(() {
2477 2478 2479 2480
          assert(_currentBottomSheet == null);
        });
        return true;
      }());
2481
    }
2482 2483
  }

2484 2485 2486 2487
  void _updatePersistentBottomSheet() {
    _currentBottomSheetKey.currentState!.setState(() {});
  }

2488 2489 2490
  PersistentBottomSheetController<T> _buildBottomSheet<T>(
    WidgetBuilder builder,
    bool isPersistent, {
2491 2492 2493 2494 2495
    required AnimationController animationController,
    Color? backgroundColor,
    double? elevation,
    ShapeBorder? shape,
    Clip? clipBehavior,
2496
    BoxConstraints? constraints,
2497 2498 2499 2500
  }) {
    assert(() {
      if (widget.bottomSheet != null && isPersistent && _currentBottomSheet != null) {
        throw FlutterError(
2501
          'Scaffold.bottomSheet cannot be specified while a bottom sheet '
2502
          'displayed with showBottomSheet() is still visible.\n'
2503
          'Rebuild the Scaffold with a null bottomSheet before calling showBottomSheet().',
2504 2505 2506 2507 2508
        );
      }
      return true;
    }());

2509
    final Completer<T> completer = Completer<T>();
2510
    final GlobalKey<_StandardBottomSheetState> bottomSheetKey = GlobalKey<_StandardBottomSheetState>();
2511
    late _StandardBottomSheet bottomSheet;
2512

2513
    bool removedEntry = false;
2514
    void _removeCurrentBottomSheet() {
2515 2516 2517 2518
      removedEntry = true;
      if (_currentBottomSheet == null) {
        return;
      }
2519
      assert(_currentBottomSheet!._widget == bottomSheet);
2520
      assert(bottomSheetKey.currentState != null);
2521 2522
      _showFloatingActionButton();

2523 2524 2525 2526
      bottomSheetKey.currentState!.close();
      setState(() {
        _currentBottomSheet = null;
      });
2527

2528 2529
      if (animationController.status != AnimationStatus.dismissed) {
        _dismissedBottomSheets.add(bottomSheet);
2530
      }
2531
      completer.complete();
2532 2533
    }

2534
    final LocalHistoryEntry? entry = isPersistent
2535 2536
      ? null
      : LocalHistoryEntry(onRemove: () {
2537 2538 2539 2540
          if (!removedEntry) {
            _removeCurrentBottomSheet();
          }
        });
2541

2542
    bottomSheet = _StandardBottomSheet(
2543
      key: bottomSheetKey,
2544 2545
      animationController: animationController,
      enableDrag: !isPersistent,
2546
      onClosing: () {
2547 2548 2549
        if (_currentBottomSheet == null) {
          return;
        }
2550
        assert(_currentBottomSheet!._widget == bottomSheet);
2551 2552
        if (!isPersistent && !removedEntry) {
          assert(entry != null);
2553
          entry!.remove();
2554 2555
          removedEntry = true;
        }
2556 2557
      },
      onDismissed: () {
2558 2559 2560 2561 2562
        if (_dismissedBottomSheets.contains(bottomSheet)) {
          setState(() {
            _dismissedBottomSheets.remove(bottomSheet);
          });
        }
2563
      },
2564
      builder: builder,
2565 2566
      isPersistent: isPersistent,
      backgroundColor: backgroundColor,
2567 2568
      elevation: elevation,
      shape: shape,
2569
      clipBehavior: clipBehavior,
2570
      constraints: constraints,
2571
    );
2572

2573
    if (!isPersistent)
2574
      ModalRoute.of(context)!.addLocalHistoryEntry(entry!);
2575

2576
    return PersistentBottomSheetController<T>._(
2577 2578
      bottomSheet,
      completer,
2579 2580 2581
      entry != null
        ? entry.remove
        : _removeCurrentBottomSheet,
2582
      (VoidCallback fn) { bottomSheetKey.currentState?.setState(fn); },
2583
      !isPersistent,
2584 2585 2586
    );
  }

2587 2588
  /// Shows a material design bottom sheet in the nearest [Scaffold]. To show
  /// a persistent bottom sheet, use the [Scaffold.bottomSheet].
2589 2590 2591 2592 2593 2594 2595 2596 2597
  ///
  /// Returns a controller that can be used to close and otherwise manipulate the
  /// bottom sheet.
  ///
  /// To rebuild the bottom sheet (e.g. if it is stateful), call
  /// [PersistentBottomSheetController.setState] on the controller returned by
  /// this method.
  ///
  /// The new bottom sheet becomes a [LocalHistoryEntry] for the enclosing
2598
  /// [ModalRoute] and a back button is added to the app bar of the [Scaffold]
2599 2600 2601
  /// that closes the bottom sheet.
  ///
  /// To create a persistent bottom sheet that is not a [LocalHistoryEntry] and
2602
  /// does not add a back button to the enclosing Scaffold's app bar, use the
2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613
  /// [Scaffold.bottomSheet] constructor parameter.
  ///
  /// A persistent bottom sheet shows information that supplements the primary
  /// content of the app. A persistent bottom sheet remains visible even when
  /// the user interacts with other parts of the app.
  ///
  /// A closely related widget is a modal bottom sheet, which is an alternative
  /// to a menu or a dialog and prevents the user from interacting with the rest
  /// of the app. Modal bottom sheets can be created and displayed with the
  /// [showModalBottomSheet] function.
  ///
2614
  /// {@tool dartpad --template=stateless_widget_scaffold}
2615 2616 2617 2618 2619 2620 2621 2622
  ///
  /// This example demonstrates how to use `showBottomSheet` to display a
  /// bottom sheet when a user taps a button. It also demonstrates how to
  /// close a bottom sheet using the Navigator.
  ///
  /// ```dart
  /// Widget build(BuildContext context) {
  ///   return Center(
2623
  ///     child: ElevatedButton(
2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
  ///       child: const Text('showBottomSheet'),
  ///       onPressed: () {
  ///         Scaffold.of(context).showBottomSheet<void>(
  ///           (BuildContext context) {
  ///             return Container(
  ///               height: 200,
  ///               color: Colors.amber,
  ///               child: Center(
  ///                 child: Column(
  ///                   mainAxisAlignment: MainAxisAlignment.center,
  ///                   mainAxisSize: MainAxisSize.min,
  ///                   children: <Widget>[
  ///                     const Text('BottomSheet'),
2637
  ///                     ElevatedButton(
2638
  ///                       child: const Text('Close BottomSheet'),
2639 2640 2641
  ///                       onPressed: () {
  ///                         Navigator.pop(context);
  ///                       }
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654
  ///                     )
  ///                   ],
  ///                 ),
  ///               ),
  ///             );
  ///           },
  ///         );
  ///       },
  ///     ),
  ///   );
  /// }
  /// ```
  /// {@end-tool}
2655 2656
  /// See also:
  ///
2657 2658
  ///  * [BottomSheet], which becomes the parent of the widget returned by the
  ///    `builder`.
2659 2660 2661 2662
  ///  * [showBottomSheet], which calls this method given a [BuildContext].
  ///  * [showModalBottomSheet], which can be used to display a modal bottom
  ///    sheet.
  ///  * [Scaffold.of], for information about how to obtain the [ScaffoldState].
2663
  ///  * <https://material.io/design/components/sheets-bottom.html#standard-bottom-sheet>
2664 2665
  PersistentBottomSheetController<T> showBottomSheet<T>(
    WidgetBuilder builder, {
2666 2667 2668 2669
    Color? backgroundColor,
    double? elevation,
    ShapeBorder? shape,
    Clip? clipBehavior,
2670
    BoxConstraints? constraints,
2671
    AnimationController? transitionAnimationController,
2672 2673 2674 2675
  }) {
    assert(() {
      if (widget.bottomSheet != null) {
        throw FlutterError(
2676
          'Scaffold.bottomSheet cannot be specified while a bottom sheet '
2677
          'displayed with showBottomSheet() is still visible.\n'
2678
          'Rebuild the Scaffold with a null bottomSheet before calling showBottomSheet().',
2679 2680 2681 2682 2683 2684
        );
      }
      return true;
    }());
    assert(debugCheckHasMediaQuery(context));

2685
    _closeCurrentBottomSheet();
2686
    final AnimationController controller = (transitionAnimationController ?? BottomSheet.createAnimationController(this))..forward();
2687
    setState(() {
2688 2689 2690 2691 2692
      _currentBottomSheet = _buildBottomSheet<T>(
        builder,
        false,
        animationController: controller,
        backgroundColor: backgroundColor,
2693 2694
        elevation: elevation,
        shape: shape,
2695
        clipBehavior: clipBehavior,
2696
        constraints: constraints,
2697
      );
2698
    });
2699
    return _currentBottomSheet! as PersistentBottomSheetController<T>;
2700 2701
  }

2702
  // Floating Action Button API
2703 2704 2705 2706
  late AnimationController _floatingActionButtonMoveController;
  late FloatingActionButtonAnimator _floatingActionButtonAnimator;
  FloatingActionButtonLocation? _previousFloatingActionButtonLocation;
  FloatingActionButtonLocation? _floatingActionButtonLocation;
2707

2708
  late AnimationController _floatingActionButtonVisibilityController;
2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720

  /// Gets the current value of the visibility animation for the
  /// [Scaffold.floatingActionButton].
  double get _floatingActionButtonVisibilityValue => _floatingActionButtonVisibilityController.value;

  /// Sets the current value of the visibility animation for the
  /// [Scaffold.floatingActionButton].  This value must not be null.
  set _floatingActionButtonVisibilityValue(double newValue) {
    assert(newValue != null);
    _floatingActionButtonVisibilityController.value = newValue.clamp(
      _floatingActionButtonVisibilityController.lowerBound,
      _floatingActionButtonVisibilityController.upperBound,
2721
    );
2722 2723 2724 2725 2726 2727 2728
  }

  /// Shows the [Scaffold.floatingActionButton].
  TickerFuture _showFloatingActionButton() {
    return _floatingActionButtonVisibilityController.forward();
  }

2729 2730
  // Moves the Floating Action Button to the new Floating Action Button Location.
  void _moveFloatingActionButton(final FloatingActionButtonLocation newLocation) {
2731
    FloatingActionButtonLocation? previousLocation = _floatingActionButtonLocation;
2732 2733 2734
    double restartAnimationFrom = 0.0;
    // If the Floating Action Button is moving right now, we need to start from a snapshot of the current transition.
    if (_floatingActionButtonMoveController.isAnimating) {
2735
      previousLocation = _TransitionSnapshotFabLocation(_previousFloatingActionButtonLocation!, _floatingActionButtonLocation!, _floatingActionButtonAnimator, _floatingActionButtonMoveController.value);
2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748
      restartAnimationFrom = _floatingActionButtonAnimator.getAnimationRestart(_floatingActionButtonMoveController.value);
    }

    setState(() {
      _previousFloatingActionButtonLocation = previousLocation;
      _floatingActionButtonLocation = newLocation;
    });

    // Animate the motion even when the fab is null so that if the exit animation is running,
    // the old fab will start the motion transition while it exits instead of jumping to the
    // new position.
    _floatingActionButtonMoveController.forward(from: restartAnimationFrom);
  }
2749

2750
  // iOS FEATURES - status bar tap, back gesture
2751

2752
  // On iOS, tapping the status bar scrolls the app's primary scrollable to the
2753
  // top. We implement this by looking up the  primary scroll controller and
2754 2755
  // scrolling it to the top when tapped.
  void _handleStatusBarTap() {
2756 2757
    final ScrollController? _primaryScrollController = PrimaryScrollController.of(context);
    if (_primaryScrollController != null && _primaryScrollController.hasClients) {
2758 2759 2760 2761
      _primaryScrollController.animateTo(
        0.0,
        duration: const Duration(milliseconds: 300),
        curve: Curves.linear, // TODO(ianh): Use a more appropriate curve.
2762 2763 2764 2765
      );
    }
  }

2766 2767
  // INTERNALS

2768
  late _ScaffoldGeometryNotifier _geometryNotifier;
2769

2770
  bool get _resizeToAvoidBottomInset {
2771
    return widget.resizeToAvoidBottomInset ?? true;
2772 2773
  }

2774 2775 2776
  @override
  void initState() {
    super.initState();
2777
    _geometryNotifier = _ScaffoldGeometryNotifier(const ScaffoldGeometry(), context);
2778 2779 2780
    _floatingActionButtonLocation = widget.floatingActionButtonLocation ?? _kDefaultFloatingActionButtonLocation;
    _floatingActionButtonAnimator = widget.floatingActionButtonAnimator ?? _kDefaultFloatingActionButtonAnimator;
    _previousFloatingActionButtonLocation = _floatingActionButtonLocation;
2781
    _floatingActionButtonMoveController = AnimationController(
2782 2783 2784 2785
      vsync: this,
      lowerBound: 0.0,
      upperBound: 1.0,
      value: 1.0,
2786 2787
      duration: kFloatingActionButtonSegue * 2,
    );
2788 2789 2790 2791 2792

    _floatingActionButtonVisibilityController = AnimationController(
      duration: kFloatingActionButtonSegue,
      vsync: this,
    );
2793 2794
  }

2795 2796 2797 2798 2799 2800 2801 2802 2803
  @override
  void didUpdateWidget(Scaffold oldWidget) {
    // Update the Floating Action Button Animator, and then schedule the Floating Action Button for repositioning.
    if (widget.floatingActionButtonAnimator != oldWidget.floatingActionButtonAnimator) {
      _floatingActionButtonAnimator = widget.floatingActionButtonAnimator ?? _kDefaultFloatingActionButtonAnimator;
    }
    if (widget.floatingActionButtonLocation != oldWidget.floatingActionButtonLocation) {
      _moveFloatingActionButton(widget.floatingActionButtonLocation ?? _kDefaultFloatingActionButtonLocation);
    }
2804 2805 2806
    if (widget.bottomSheet != oldWidget.bottomSheet) {
      assert(() {
        if (widget.bottomSheet != null && _currentBottomSheet?._isLocalHistoryEntry == true) {
2807 2808 2809
          throw FlutterError.fromParts(<DiagnosticsNode>[
            ErrorSummary(
              'Scaffold.bottomSheet cannot be specified while a bottom sheet displayed '
2810
              'with showBottomSheet() is still visible.',
2811 2812 2813 2814
            ),
            ErrorHint(
              'Use the PersistentBottomSheetController '
              'returned by showBottomSheet() to close the old bottom sheet before creating '
2815
              'a Scaffold with a (non null) bottomSheet.',
2816 2817
            ),
          ]);
2818 2819 2820
        }
        return true;
      }());
2821 2822 2823 2824 2825 2826 2827
      if (widget.bottomSheet == null) {
        _closeCurrentBottomSheet();
      } else if (widget.bottomSheet != null && oldWidget.bottomSheet == null) {
        _maybeBuildPersistentBottomSheet();
      } else {
        _updatePersistentBottomSheet();
      }
2828
    }
2829 2830 2831
    super.didUpdateWidget(oldWidget);
  }

2832 2833
  @override
  void didChangeDependencies() {
2834 2835
    // Using maybeOf is valid here since both the Scaffold and ScaffoldMessenger
    // are currently available for managing SnackBars.
2836
    final ScaffoldMessengerState? _currentScaffoldMessenger = ScaffoldMessenger.maybeOf(context);
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846
    // If our ScaffoldMessenger has changed, unregister with the old one first.
    if (_scaffoldMessenger != null &&
      (_currentScaffoldMessenger == null || _scaffoldMessenger != _currentScaffoldMessenger)) {
      _scaffoldMessenger?._unregister(this);
    }
    // Register with the current ScaffoldMessenger, if there is one.
    _scaffoldMessenger = _currentScaffoldMessenger;
    _scaffoldMessenger?._register(this);

    // TODO(Piinks): Remove old SnackBar API after migrating ScaffoldMessenger
2847
    final MediaQueryData mediaQuery = MediaQuery.of(context);
2848 2849 2850 2851 2852 2853 2854
    // If we transition from accessible navigation to non-accessible navigation
    // and there is a SnackBar that would have timed out that has already
    // completed its timer, dismiss that SnackBar. If the timer hasn't finished
    // yet, let it timeout as normal.
    if (_accessibleNavigation == true
      && !mediaQuery.accessibleNavigation
      && _snackBarTimer != null
2855
      && !_snackBarTimer!.isActive) {
2856 2857 2858
      hideCurrentSnackBar(reason: SnackBarClosedReason.timeout);
    }
    _accessibleNavigation = mediaQuery.accessibleNavigation;
2859

2860
    _maybeBuildPersistentBottomSheet();
2861 2862 2863
    super.didChangeDependencies();
  }

2864 2865
  @override
  void dispose() {
2866
    // TODO(Piinks): Remove old SnackBar API after migrating ScaffoldMessenger
2867 2868 2869
    _snackBarController?.dispose();
    _snackBarTimer?.cancel();
    _snackBarTimer = null;
2870

2871
    _geometryNotifier.dispose();
2872
    for (final _StandardBottomSheet bottomSheet in _dismissedBottomSheets) {
2873
      bottomSheet.animationController.dispose();
2874 2875
    }
    if (_currentBottomSheet != null) {
2876
      _currentBottomSheet!._widget.animationController.dispose();
2877
    }
2878
    _floatingActionButtonMoveController.dispose();
2879
    _floatingActionButtonVisibilityController.dispose();
2880
    _scaffoldMessenger?._unregister(this);
2881 2882 2883
    super.dispose();
  }

2884 2885
  void _addIfNonNull(
    List<LayoutId> children,
2886
    Widget? child,
2887
    Object childId, {
2888 2889 2890 2891
    required bool removeLeftPadding,
    required bool removeTopPadding,
    required bool removeRightPadding,
    required bool removeBottomPadding,
2892
    bool removeBottomInset = false,
2893
    bool maintainBottomViewPadding = false,
Ian Hickson's avatar
Ian Hickson committed
2894
  }) {
2895
    MediaQueryData data = MediaQuery.of(context).removePadding(
2896 2897 2898 2899 2900 2901 2902 2903
      removeLeft: removeLeftPadding,
      removeTop: removeTopPadding,
      removeRight: removeRightPadding,
      removeBottom: removeBottomPadding,
    );
    if (removeBottomInset)
      data = data.removeViewInsets(removeBottom: true);

2904 2905
    if (maintainBottomViewPadding && data.viewInsets.bottom != 0.0) {
      data = data.copyWith(
2906
        padding: data.padding.copyWith(bottom: data.viewPadding.bottom),
2907 2908 2909
      );
    }

Ian Hickson's avatar
Ian Hickson committed
2910 2911
    if (child != null) {
      children.add(
2912
        LayoutId(
Ian Hickson's avatar
Ian Hickson committed
2913
          id: childId,
2914
          child: MediaQuery(data: data, child: child),
Ian Hickson's avatar
Ian Hickson committed
2915 2916 2917
        ),
      );
    }
2918 2919
  }

jslavitz's avatar
jslavitz committed
2920 2921 2922 2923 2924
  void _buildEndDrawer(List<LayoutId> children, TextDirection textDirection) {
    if (widget.endDrawer != null) {
      assert(hasEndDrawer);
      _addIfNonNull(
        children,
2925
        DrawerController(
jslavitz's avatar
jslavitz committed
2926 2927 2928
          key: _endDrawerKey,
          alignment: DrawerAlignment.end,
          drawerCallback: _endDrawerOpenedCallback,
2929
          dragStartBehavior: widget.drawerDragStartBehavior,
2930
          scrimColor: widget.drawerScrimColor,
2931
          edgeDragWidth: widget.drawerEdgeDragWidth,
2932
          enableOpenDragGesture: widget.endDrawerEnableOpenDragGesture,
2933
          isDrawerOpen: _endDrawerOpened.value,
2934
          child: widget.endDrawer!,
jslavitz's avatar
jslavitz committed
2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950
        ),
        _ScaffoldSlot.endDrawer,
        // remove the side padding from the side we're not touching
        removeLeftPadding: textDirection == TextDirection.ltr,
        removeTopPadding: false,
        removeRightPadding: textDirection == TextDirection.rtl,
        removeBottomPadding: false,
      );
    }
  }

  void _buildDrawer(List<LayoutId> children, TextDirection textDirection) {
    if (widget.drawer != null) {
      assert(hasDrawer);
      _addIfNonNull(
        children,
2951
        DrawerController(
jslavitz's avatar
jslavitz committed
2952 2953 2954
          key: _drawerKey,
          alignment: DrawerAlignment.start,
          drawerCallback: _drawerOpenedCallback,
2955
          dragStartBehavior: widget.drawerDragStartBehavior,
2956
          scrimColor: widget.drawerScrimColor,
2957
          edgeDragWidth: widget.drawerEdgeDragWidth,
2958
          enableOpenDragGesture: widget.drawerEnableOpenDragGesture,
2959
          isDrawerOpen: _drawerOpened.value,
2960
          child: widget.drawer!,
jslavitz's avatar
jslavitz committed
2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971
        ),
        _ScaffoldSlot.drawer,
        // remove the side padding from the side we're not touching
        removeLeftPadding: textDirection == TextDirection.rtl,
        removeTopPadding: false,
        removeRightPadding: textDirection == TextDirection.ltr,
        removeBottomPadding: false,
      );
    }
  }

2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988
  bool _showBodyScrim = false;
  Color _bodyScrimColor = Colors.black;

  /// Whether to show a [ModalBarrier] over the body of the scaffold.
  ///
  /// The `value` parameter must not be null.
  void showBodyScrim(bool value, double opacity) {
    assert(value != null);
    if (_showBodyScrim == value && _bodyScrimColor.opacity == opacity) {
      return;
    }
    setState(() {
      _showBodyScrim = value;
      _bodyScrimColor = Colors.black.withOpacity(opacity);
    });
  }

2989
  @override
Adam Barth's avatar
Adam Barth committed
2990
  Widget build(BuildContext context) {
2991
    assert(debugCheckHasMediaQuery(context));
Ian Hickson's avatar
Ian Hickson committed
2992
    assert(debugCheckHasDirectionality(context));
2993
    final MediaQueryData mediaQuery = MediaQuery.of(context);
2994
    final ThemeData themeData = Theme.of(context);
2995
    final TextDirection textDirection = Directionality.of(context);
2996

2997 2998
    // TODO(Piinks): Remove old SnackBar API after migrating ScaffoldMessenger
    _accessibleNavigation = mediaQuery.accessibleNavigation;
2999
    if (_snackBars.isNotEmpty) {
3000
      final ModalRoute<dynamic>? route = ModalRoute.of(context);
3001
      if (route == null || route.isCurrent) {
3002
        if (_snackBarController!.isCompleted && _snackBarTimer == null) {
3003 3004
          final SnackBar snackBar = _snackBars.first._widget;
          _snackBarTimer = Timer(snackBar.duration, () {
3005 3006 3007 3008
            assert(
              _snackBarController!.status == AnimationStatus.forward ||
                _snackBarController!.status == AnimationStatus.completed,
            );
3009
            // Look up MediaQuery again in case the setting changed.
3010
            final MediaQueryData mediaQuery = MediaQuery.of(context);
3011 3012 3013 3014 3015 3016 3017 3018 3019 3020
            if (mediaQuery.accessibleNavigation && snackBar.action != null)
              return;
            hideCurrentSnackBar(reason: SnackBarClosedReason.timeout);
          });
        }
      } else {
        _snackBarTimer?.cancel();
        _snackBarTimer = null;
      }
    }
3021

3022
    final List<LayoutId> children = <LayoutId>[];
Ian Hickson's avatar
Ian Hickson committed
3023 3024
    _addIfNonNull(
      children,
3025 3026 3027
      widget.body == null ? null : _BodyBuilder(
        extendBody: widget.extendBody,
        extendBodyBehindAppBar: widget.extendBodyBehindAppBar,
3028
        body: widget.body!,
3029
      ),
Ian Hickson's avatar
Ian Hickson committed
3030 3031 3032 3033
      _ScaffoldSlot.body,
      removeLeftPadding: false,
      removeTopPadding: widget.appBar != null,
      removeRightPadding: false,
3034 3035
      removeBottomPadding: widget.bottomNavigationBar != null || widget.persistentFooterButtons != null,
      removeBottomInset: _resizeToAvoidBottomInset,
Ian Hickson's avatar
Ian Hickson committed
3036
    );
3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050
    if (_showBodyScrim) {
      _addIfNonNull(
        children,
        ModalBarrier(
          dismissible: false,
          color: _bodyScrimColor,
        ),
        _ScaffoldSlot.bodyScrim,
        removeLeftPadding: true,
        removeTopPadding: true,
        removeRightPadding: true,
        removeBottomPadding: true,
      );
    }
3051

3052
    if (widget.appBar != null) {
3053
      final double topPadding = widget.primary ? mediaQuery.padding.top : 0.0;
3054
      _appBarMaxHeight = AppBar.preferredHeightFor(context, widget.appBar!.preferredSize) + topPadding;
3055
      assert(_appBarMaxHeight! >= 0.0 && _appBarMaxHeight!.isFinite);
3056 3057
      _addIfNonNull(
        children,
3058
        ConstrainedBox(
3059
          constraints: BoxConstraints(maxHeight: _appBarMaxHeight!),
3060
          child: FlexibleSpaceBar.createSettings(
3061 3062
            currentExtent: _appBarMaxHeight!,
            child: widget.appBar!,
3063
          ),
3064 3065
        ),
        _ScaffoldSlot.appBar,
Ian Hickson's avatar
Ian Hickson committed
3066 3067 3068 3069
        removeLeftPadding: false,
        removeTopPadding: false,
        removeRightPadding: false,
        removeBottomPadding: true,
3070 3071
      );
    }
3072

3073
    bool isSnackBarFloating = false;
3074
    double? snackBarWidth;
3075 3076 3077 3078 3079 3080 3081
    // We should only be using one API for SnackBars. Currently, we can use the
    // Scaffold, which creates a SnackBar queue (_snackBars), or the
    // ScaffoldMessenger, which sends a SnackBar to descendant Scaffolds.
    // (_messengerSnackBar).
    assert(
      _snackBars.isEmpty || _messengerSnackBar == null,
      'Only one API should be used to manage SnackBars. The ScaffoldMessenger is '
3082
      'the preferred API instead of the Scaffold methods.',
3083 3084
    );

3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103
    if (_currentBottomSheet != null || _dismissedBottomSheets.isNotEmpty) {
      final Widget stack = Stack(
        alignment: Alignment.bottomCenter,
        children: <Widget>[
          ..._dismissedBottomSheets,
          if (_currentBottomSheet != null) _currentBottomSheet!._widget,
        ],
      );
      _addIfNonNull(
        children,
        stack,
        _ScaffoldSlot.bottomSheet,
        removeLeftPadding: false,
        removeTopPadding: true,
        removeRightPadding: false,
        removeBottomPadding: _resizeToAvoidBottomInset,
      );
    }

3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125
    // SnackBar set by ScaffoldMessenger
    if (_messengerSnackBar != null) {
      final SnackBarBehavior snackBarBehavior = _messengerSnackBar?._widget.behavior
        ?? themeData.snackBarTheme.behavior
        ?? SnackBarBehavior.fixed;
      isSnackBarFloating = snackBarBehavior == SnackBarBehavior.floating;
      snackBarWidth = _messengerSnackBar?._widget.width;

      _addIfNonNull(
        children,
        _messengerSnackBar?._widget,
        _ScaffoldSlot.snackBar,
        removeLeftPadding: false,
        removeTopPadding: true,
        removeRightPadding: false,
        removeBottomPadding: widget.bottomNavigationBar != null || widget.persistentFooterButtons != null,
        maintainBottomViewPadding: !_resizeToAvoidBottomInset,
      );
    }

    // SnackBar set by Scaffold
    // TODO(Piinks): Remove old SnackBar API after migrating ScaffoldMessenger
3126 3127
    if (_snackBars.isNotEmpty) {
      final SnackBarBehavior snackBarBehavior = _snackBars.first._widget.behavior
3128 3129 3130
        ?? themeData.snackBarTheme.behavior
        ?? SnackBarBehavior.fixed;
      isSnackBarFloating = snackBarBehavior == SnackBarBehavior.floating;
3131
      snackBarWidth = _snackBars.first._widget.width;
3132

Ian Hickson's avatar
Ian Hickson committed
3133 3134
      _addIfNonNull(
        children,
3135
        _snackBars.first._widget,
Ian Hickson's avatar
Ian Hickson committed
3136 3137 3138 3139
        _ScaffoldSlot.snackBar,
        removeLeftPadding: false,
        removeTopPadding: true,
        removeRightPadding: false,
3140
        removeBottomPadding: widget.bottomNavigationBar != null || widget.persistentFooterButtons != null,
3141
        maintainBottomViewPadding: !_resizeToAvoidBottomInset,
Ian Hickson's avatar
Ian Hickson committed
3142 3143
      );
    }
3144

3145
    if (widget.persistentFooterButtons != null) {
Ian Hickson's avatar
Ian Hickson committed
3146 3147
      _addIfNonNull(
        children,
3148 3149 3150
        Container(
          decoration: BoxDecoration(
            border: Border(
3151
              top: Divider.createBorderSide(context, width: 1.0),
3152 3153
            ),
          ),
3154
          child: SafeArea(
3155
            top: false,
3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
            child: IntrinsicHeight(
              child: Container(
                alignment: AlignmentDirectional.centerEnd,
                padding: const EdgeInsets.all(8),
                child: OverflowBar(
                  spacing: 8,
                  overflowAlignment: OverflowBarAlignment.end,
                  children: widget.persistentFooterButtons!,
                ),
              ),
3166 3167 3168
            ),
          ),
        ),
Ian Hickson's avatar
Ian Hickson committed
3169 3170 3171 3172
        _ScaffoldSlot.persistentFooter,
        removeLeftPadding: false,
        removeTopPadding: true,
        removeRightPadding: false,
3173
        removeBottomPadding: false,
3174
        maintainBottomViewPadding: !_resizeToAvoidBottomInset,
Ian Hickson's avatar
Ian Hickson committed
3175
      );
3176 3177
    }

3178
    if (widget.bottomNavigationBar != null) {
Ian Hickson's avatar
Ian Hickson committed
3179 3180 3181 3182 3183 3184 3185
      _addIfNonNull(
        children,
        widget.bottomNavigationBar,
        _ScaffoldSlot.bottomNavigationBar,
        removeLeftPadding: false,
        removeTopPadding: true,
        removeRightPadding: false,
3186
        removeBottomPadding: false,
3187
        maintainBottomViewPadding: !_resizeToAvoidBottomInset,
Ian Hickson's avatar
Ian Hickson committed
3188
      );
3189
    }
3190

Ian Hickson's avatar
Ian Hickson committed
3191 3192
    _addIfNonNull(
      children,
3193
      _FloatingActionButtonTransition(
3194 3195
        fabMoveAnimation: _floatingActionButtonMoveController,
        fabMotionAnimator: _floatingActionButtonAnimator,
3196
        geometryNotifier: _geometryNotifier,
3197
        currentController: _floatingActionButtonVisibilityController,
3198
        child: widget.floatingActionButton,
Ian Hickson's avatar
Ian Hickson committed
3199 3200 3201 3202 3203 3204 3205
      ),
      _ScaffoldSlot.floatingActionButton,
      removeLeftPadding: true,
      removeTopPadding: true,
      removeRightPadding: true,
      removeBottomPadding: true,
    );
3206

3207 3208
    switch (themeData.platform) {
      case TargetPlatform.iOS:
3209
      case TargetPlatform.macOS:
3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226
        _addIfNonNull(
          children,
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: _handleStatusBarTap,
            // iOS accessibility automatically adds scroll-to-top to the clock in the status bar
            excludeFromSemantics: true,
          ),
          _ScaffoldSlot.statusBar,
          removeLeftPadding: false,
          removeTopPadding: true,
          removeRightPadding: false,
          removeBottomPadding: true,
        );
        break;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
3227 3228
      case TargetPlatform.linux:
      case TargetPlatform.windows:
3229
        break;
3230 3231
    }

3232
    if (_endDrawerOpened.value) {
jslavitz's avatar
jslavitz committed
3233 3234 3235 3236 3237
      _buildDrawer(children, textDirection);
      _buildEndDrawer(children, textDirection);
    } else {
      _buildEndDrawer(children, textDirection);
      _buildDrawer(children, textDirection);
3238 3239
    }

3240 3241
    // The minimum insets for contents of the Scaffold to keep visible.
    final EdgeInsets minInsets = mediaQuery.padding.copyWith(
3242
      bottom: _resizeToAvoidBottomInset ? mediaQuery.viewInsets.bottom : 0.0,
3243
    );
3244

3245 3246 3247 3248 3249 3250
    // The minimum viewPadding for interactive elements positioned by the
    // Scaffold to keep within safe interactive areas.
    final EdgeInsets minViewPadding = mediaQuery.viewPadding.copyWith(
      bottom: _resizeToAvoidBottomInset &&  mediaQuery.viewInsets.bottom != 0.0 ? 0.0 : null,
    );

3251
    // extendBody locked when keyboard is open
3252
    final bool _extendBody = minInsets.bottom <= 0 && widget.extendBody;
3253

3254
    return _ScaffoldScope(
3255
      hasDrawer: hasDrawer,
3256
      geometryNotifier: _geometryNotifier,
3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
      child: ScrollNotificationObserver(
        child: Material(
          color: widget.backgroundColor ?? themeData.scaffoldBackgroundColor,
          child: AnimatedBuilder(animation: _floatingActionButtonMoveController, builder: (BuildContext context, Widget? child) {
            return CustomMultiChildLayout(
              delegate: _ScaffoldLayout(
                extendBody: _extendBody,
                extendBodyBehindAppBar: widget.extendBodyBehindAppBar,
                minInsets: minInsets,
                minViewPadding: minViewPadding,
                currentFloatingActionButtonLocation: _floatingActionButtonLocation!,
                floatingActionButtonMoveAnimationProgress: _floatingActionButtonMoveController.value,
                floatingActionButtonMotionAnimator: _floatingActionButtonAnimator,
                geometryNotifier: _geometryNotifier,
                previousFloatingActionButtonLocation: _previousFloatingActionButtonLocation!,
                textDirection: textDirection,
                isSnackBarFloating: isSnackBarFloating,
                snackBarWidth: snackBarWidth,
              ),
3276
              children: children,
3277 3278 3279
            );
          }),
        ),
3280
      ),
3281
    );
3282
  }
3283
}
3284

3285 3286
/// An interface for controlling a feature of a [Scaffold].
///
3287 3288
/// Commonly obtained from [ScaffoldMessengerState.showSnackBar] or
/// [ScaffoldState.showBottomSheet].
3289
class ScaffoldFeatureController<T extends Widget, U> {
3290 3291
  const ScaffoldFeatureController._(this._widget, this._completer, this.close, this.setState);
  final T _widget;
3292
  final Completer<U> _completer;
3293 3294

  /// Completes when the feature controlled by this object is no longer visible.
3295
  Future<U> get closed => _completer.future;
3296 3297 3298 3299 3300

  /// Remove the feature (e.g., bottom sheet or snack bar) from the scaffold.
  final VoidCallback close;

  /// Mark the feature (e.g., bottom sheet or snack bar) as needing to rebuild.
3301
  final StateSetter? setState;
3302 3303
}

3304 3305
// TODO(guidezpl): Look into making this public. A copy of this class is in
//  bottom_sheet.dart, for now, https://github.com/flutter/flutter/issues/51627
3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352
/// A curve that progresses linearly until a specified [startingPoint], at which
/// point [curve] will begin. Unlike [Interval], [curve] will not start at zero,
/// but will use [startingPoint] as the Y position.
///
/// For example, if [startingPoint] is set to `0.5`, and [curve] is set to
/// [Curves.easeOut], then the bottom-left quarter of the curve will be a
/// straight line, and the top-right quarter will contain the entire contents of
/// [Curves.easeOut].
///
/// This is useful in situations where a widget must track the user's finger
/// (which requires a linear animation), and afterwards can be flung using a
/// curve specified with the [curve] argument, after the finger is released. In
/// such a case, the value of [startingPoint] would be the progress of the
/// animation at the time when the finger was released.
///
/// The [startingPoint] and [curve] arguments must not be null.
class _BottomSheetSuspendedCurve extends ParametricCurve<double> {
  /// Creates a suspended curve.
  const _BottomSheetSuspendedCurve(
      this.startingPoint, {
        this.curve = Curves.easeOutCubic,
      }) : assert(startingPoint != null),
        assert(curve != null);

  /// The progress value at which [curve] should begin.
  ///
  /// This defaults to [Curves.easeOutCubic].
  final double startingPoint;

  /// The curve to use when [startingPoint] is reached.
  final Curve curve;

  @override
  double transform(double t) {
    assert(t >= 0.0 && t <= 1.0);
    assert(startingPoint >= 0.0 && startingPoint <= 1.0);

    if (t < startingPoint) {
      return t;
    }

    if (t == 1.0) {
      return t;
    }

    final double curveProgress = (t - startingPoint) / (1 - startingPoint);
    final double transformed = curve.transform(curveProgress);
3353
    return lerpDouble(startingPoint, 1, transformed)!;
3354 3355 3356 3357 3358 3359 3360 3361
  }

  @override
  String toString() {
    return '${describeIdentity(this)}($startingPoint, $curve)';
  }
}

3362 3363
class _StandardBottomSheet extends StatefulWidget {
  const _StandardBottomSheet({
3364 3365
    Key? key,
    required this.animationController,
3366
    this.enableDrag = true,
3367 3368 3369
    required this.onClosing,
    required this.onDismissed,
    required this.builder,
3370 3371
    this.isPersistent = false,
    this.backgroundColor,
3372 3373
    this.elevation,
    this.shape,
3374
    this.clipBehavior,
3375
    this.constraints,
3376 3377
  }) : super(key: key);

3378
  final AnimationController animationController; // we control it, but it must be disposed by whoever created it.
3379
  final bool enableDrag;
3380 3381
  final VoidCallback? onClosing;
  final VoidCallback? onDismissed;
3382
  final WidgetBuilder builder;
3383
  final bool isPersistent;
3384 3385 3386 3387
  final Color? backgroundColor;
  final double? elevation;
  final ShapeBorder? shape;
  final Clip? clipBehavior;
3388
  final BoxConstraints? constraints;
3389

3390
  @override
3391
  _StandardBottomSheetState createState() => _StandardBottomSheetState();
3392 3393
}

3394
class _StandardBottomSheetState extends State<_StandardBottomSheet> {
3395 3396
  ParametricCurve<double> animationCurve = _standardBottomSheetCurve;

3397
  @override
3398 3399
  void initState() {
    super.initState();
3400
    assert(widget.animationController != null);
3401 3402 3403 3404
    assert(
      widget.animationController.status == AnimationStatus.forward
        || widget.animationController.status == AnimationStatus.completed,
    );
3405
    widget.animationController.addStatusListener(_handleStatusChange);
3406 3407
  }

3408
  @override
3409
  void didUpdateWidget(_StandardBottomSheet oldWidget) {
3410 3411
    super.didUpdateWidget(oldWidget);
    assert(widget.animationController == oldWidget.animationController);
3412 3413
  }

3414
  void close() {
3415
    assert(widget.animationController != null);
3416
    widget.animationController.reverse();
3417
    widget.onClosing?.call();
3418 3419
  }

3420 3421 3422 3423 3424
  void _handleDragStart(DragStartDetails details) {
    // Allow the bottom sheet to track the user's finger accurately.
    animationCurve = Curves.linear;
  }

3425
  void _handleDragEnd(DragEndDetails details, { bool? isClosing }) {
3426 3427
    // Allow the bottom sheet to animate smoothly from its current position.
    animationCurve = _BottomSheetSuspendedCurve(
3428
      widget.animationController.value,
3429 3430 3431 3432
      curve: _standardBottomSheetCurve,
    );
  }

3433
  void _handleStatusChange(AnimationStatus status) {
3434 3435
    if (status == AnimationStatus.dismissed) {
      widget.onDismissed?.call();
3436 3437 3438 3439 3440
    }
  }

  bool extentChanged(DraggableScrollableNotification notification) {
    final double extentRemaining = 1.0 - notification.extent;
3441
    final ScaffoldState scaffold = Scaffold.of(context);
3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465
    if (extentRemaining < _kBottomSheetDominatesPercentage) {
      scaffold._floatingActionButtonVisibilityValue = extentRemaining * _kBottomSheetDominatesPercentage * 10;
      scaffold.showBodyScrim(true,  math.max(
        _kMinBottomSheetScrimOpacity,
        _kMaxBottomSheetScrimOpacity - scaffold._floatingActionButtonVisibilityValue,
      ));
    } else {
      scaffold._floatingActionButtonVisibilityValue = 1.0;
      scaffold.showBodyScrim(false, 0.0);
    }
    // If the Scaffold.bottomSheet != null, we're a persistent bottom sheet.
    if (notification.extent == notification.minExtent && scaffold.widget.bottomSheet == null) {
      close();
    }
    return false;
  }

  Widget _wrapBottomSheet(Widget bottomSheet) {
    return Semantics(
      container: true,
      onDismiss: close,
      child:  NotificationListener<DraggableScrollableNotification>(
        onNotification: extentChanged,
        child: bottomSheet,
3466
      ),
3467
    );
3468 3469
  }

3470
  @override
3471
  Widget build(BuildContext context) {
3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492
    return AnimatedBuilder(
      animation: widget.animationController,
      builder: (BuildContext context, Widget? child) {
        return Align(
          alignment: AlignmentDirectional.topStart,
          heightFactor: animationCurve.transform(widget.animationController.value),
          child: child,
        );
      },
      child: _wrapBottomSheet(
        BottomSheet(
          animationController: widget.animationController,
          enableDrag: widget.enableDrag,
          onDragStart: _handleDragStart,
          onDragEnd: _handleDragEnd,
          onClosing: widget.onClosing!,
          builder: widget.builder,
          backgroundColor: widget.backgroundColor,
          elevation: widget.elevation,
          shape: widget.shape,
          clipBehavior: widget.clipBehavior,
3493
          constraints: widget.constraints,
3494 3495
        ),
      ),
3496 3497 3498 3499
    );
  }

}
3500

3501
/// A [ScaffoldFeatureController] for standard bottom sheets.
3502
///
3503
/// This is the type of objects returned by [ScaffoldState.showBottomSheet].
3504 3505 3506 3507 3508
///
/// This controller is used to display both standard and persistent bottom
/// sheets. A bottom sheet is only persistent if it is set as the
/// [Scaffold.bottomSheet].
class PersistentBottomSheetController<T> extends ScaffoldFeatureController<_StandardBottomSheet, T> {
3509
  const PersistentBottomSheetController._(
3510
    _StandardBottomSheet widget,
3511 3512
    Completer<T> completer,
    VoidCallback close,
3513 3514
    StateSetter setState,
    this._isLocalHistoryEntry,
3515
  ) : super._(widget, completer, close, setState);
3516 3517

  final bool _isLocalHistoryEntry;
3518
}
3519 3520

class _ScaffoldScope extends InheritedWidget {
3521
  const _ScaffoldScope({
3522 3523 3524 3525
    Key? key,
    required this.hasDrawer,
    required this.geometryNotifier,
    required Widget child,
3526
  }) : assert(hasDrawer != null),
3527
       super(key: key, child: child);
3528 3529

  final bool hasDrawer;
3530
  final _ScaffoldGeometryNotifier geometryNotifier;
3531 3532 3533 3534 3535

  @override
  bool updateShouldNotify(_ScaffoldScope oldWidget) {
    return hasDrawer != oldWidget.hasDrawer;
  }
3536
}