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

5 6
import 'dart:math' as math;

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

import 'basic.dart';
11
import 'binding.dart';
12
import 'framework.dart';
13
import 'inherited_notifier.dart';
14
import 'layout_builder.dart';
15
import 'notification_listener.dart';
16
import 'scroll_activity.dart';
17 18
import 'scroll_context.dart';
import 'scroll_controller.dart';
19
import 'scroll_notification.dart';
20 21 22 23
import 'scroll_physics.dart';
import 'scroll_position.dart';
import 'scroll_position_with_single_context.dart';
import 'scroll_simulation.dart';
24
import 'value_listenable_builder.dart';
25 26 27

/// The signature of a method that provides a [BuildContext] and
/// [ScrollController] for building a widget that may overflow the draggable
28
/// [Axis] of the containing [DraggableScrollableSheet].
29 30 31 32 33 34 35 36 37
///
/// Users should apply the [scrollController] to a [ScrollView] subclass, such
/// as a [SingleChildScrollView], [ListView] or [GridView], to have the whole
/// sheet be draggable.
typedef ScrollableWidgetBuilder = Widget Function(
  BuildContext context,
  ScrollController scrollController,
);

38 39 40 41 42 43 44 45 46
/// Controls a [DraggableScrollableSheet].
///
/// Draggable scrollable controllers are typically stored as member variables in
/// [State] objects and are reused in each [State.build]. Controllers can only
/// be used to control one sheet at a time. A controller can be reused with a
/// new sheet if the previous sheet has been disposed.
///
/// The controller's methods cannot be used until after the controller has been
/// passed into a [DraggableScrollableSheet] and the sheet has run initState.
47 48 49 50 51 52 53 54
///
/// A [DraggableScrollableController] is a [Listenable]. It notifies its
/// listeners whenever an attached sheet changes sizes. It does not notify its
/// listeners when a sheet is first attached or when an attached sheet's
/// parameters change without affecting the sheet's current size. It does not
/// fire when [pixels] changes without [size] changing. For example, if the
/// constraints provided to an attached sheet change.
class DraggableScrollableController extends ChangeNotifier {
55
  _DraggableScrollableSheetScrollController? _attachedController;
56
  final Set<AnimationController> _animationControllers = <AnimationController>{};
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75

  /// Get the current size (as a fraction of the parent height) of the attached sheet.
  double get size {
    _assertAttached();
    return _attachedController!.extent.currentSize;
  }

  /// Get the current pixel height of the attached sheet.
  double get pixels {
    _assertAttached();
    return _attachedController!.extent.currentPixels;
  }

  /// Convert a sheet's size (fractional value of parent container height) to pixels.
  double sizeToPixels(double size) {
    _assertAttached();
    return _attachedController!.extent.sizeToPixels(size);
  }

76 77 78 79 80 81 82 83
  /// Returns Whether any [DraggableScrollableController] objects have attached themselves to the
  /// [DraggableScrollableSheet].
  ///
  /// If this is false, then members that interact with the [ScrollPosition],
  /// such as [sizeToPixels], [size], [animateTo], and [jumpTo], must not be
  /// called.
  bool get isAttached => _attachedController != null && _attachedController!.hasClients;

84 85 86 87 88 89
  /// Convert a sheet's pixel height to size (fractional value of parent container height).
  double pixelsToSize(double pixels) {
    _assertAttached();
    return _attachedController!.extent.pixelsToSize(pixels);
  }

90 91
  /// Animates the attached sheet from its current size to the given [size], a
  /// fractional value of the parent container's height.
92 93 94 95 96 97 98 99 100 101 102 103 104
  ///
  /// Any active sheet animation is canceled. If the sheet's internal scrollable
  /// is currently animating (e.g. responding to a user fling), that animation is
  /// canceled as well.
  ///
  /// An animation will be interrupted whenever the user attempts to scroll
  /// manually, whenever another activity is started, or when the sheet hits its
  /// max or min size (e.g. if you animate to 1 but the max size is .8, the
  /// animation will stop playing when it reaches .8).
  ///
  /// The duration must not be zero. To jump to a particular value without an
  /// animation, use [jumpTo].
  ///
105 106 107
  /// The sheet will not snap after calling [animateTo] even if [DraggableScrollableSheet.snap]
  /// is true. Snapping only occurs after user drags.
  ///
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
  /// When calling [animateTo] in widget tests, `await`ing the returned
  /// [Future] may cause the test to hang and timeout. Instead, use
  /// [WidgetTester.pumpAndSettle].
  Future<void> animateTo(
    double size, {
    required Duration duration,
    required Curve curve,
  }) async {
    _assertAttached();
    assert(size >= 0 && size <= 1);
    assert(duration != Duration.zero);
    final AnimationController animationController = AnimationController.unbounded(
      vsync: _attachedController!.position.context.vsync,
      value: _attachedController!.extent.currentSize,
    );
123
    _animationControllers.add(animationController);
124 125 126
    _attachedController!.position.goIdle();
    // This disables any snapping until the next user interaction with the sheet.
    _attachedController!.extent.hasDragged = false;
127
    _attachedController!.extent.hasChanged = true;
128 129 130 131 132 133
    _attachedController!.extent.startActivity(onCanceled: () {
      // Don't stop the controller if it's already finished and may have been disposed.
      if (animationController.isAnimating) {
        animationController.stop();
      }
    });
134
    animationController.addListener(() {
135 136 137 138 139
      _attachedController!.extent.updateSize(
        animationController.value,
        _attachedController!.position.context.notificationContext!,
      );
    });
140 141 142 143 144
    await animationController.animateTo(
      clampDouble(size, _attachedController!.extent.minSize, _attachedController!.extent.maxSize),
      duration: duration,
      curve: curve,
    );
145 146 147 148 149 150 151 152 153 154 155
  }

  /// Jumps the attached sheet from its current size to the given [size], a
  /// fractional value of the parent container's height.
  ///
  /// If [size] is outside of a the attached sheet's min or max child size,
  /// [jumpTo] will jump the sheet to the nearest valid size instead.
  ///
  /// Any active sheet animation is canceled. If the sheet's inner scrollable
  /// is currently animating (e.g. responding to a user fling), that animation is
  /// canceled as well.
156 157 158
  ///
  /// The sheet will not snap after calling [jumpTo] even if [DraggableScrollableSheet.snap]
  /// is true. Snapping only occurs after user drags.
159 160 161 162 163 164 165
  void jumpTo(double size) {
    _assertAttached();
    assert(size >= 0 && size <= 1);
    // Call start activity to interrupt any other playing activities.
    _attachedController!.extent.startActivity(onCanceled: () {});
    _attachedController!.position.goIdle();
    _attachedController!.extent.hasDragged = false;
166
    _attachedController!.extent.hasChanged = true;
167 168 169 170 171 172 173 174 175 176 177
    _attachedController!.extent.updateSize(size, _attachedController!.position.context.notificationContext!);
  }

  /// Reset the attached sheet to its initial size (see: [DraggableScrollableSheet.initialChildSize]).
  void reset() {
    _assertAttached();
    _attachedController!.reset();
  }

  void _assertAttached() {
    assert(
178
      isAttached,
179 180 181 182 183 184 185 186
      'DraggableScrollableController is not attached to a sheet. A DraggableScrollableController '
        'must be used in a DraggableScrollableSheet before any of its methods are called.',
    );
  }

  void _attach(_DraggableScrollableSheetScrollController scrollController) {
    assert(_attachedController == null, 'Draggable scrollable controller is already attached to a sheet.');
    _attachedController = scrollController;
187
    _attachedController!.extent._currentSize.addListener(notifyListeners);
188
    _attachedController!.onPositionDetached = _disposeAnimationControllers;
189 190 191 192 193 194 195 196 197 198 199 200
  }

  void _onExtentReplaced(_DraggableSheetExtent previousExtent) {
    // When the extent has been replaced, the old extent is already disposed and
    // the controller will point to a new extent. We have to add our listener to
    // the new extent.
    _attachedController!.extent._currentSize.addListener(notifyListeners);
    if (previousExtent.currentSize != _attachedController!.extent.currentSize) {
      // The listener won't fire for a change in size between two extent
      // objects so we have to fire it manually here.
      notifyListeners();
    }
201 202
  }

xubaolin's avatar
xubaolin committed
203 204 205 206 207 208
  void _detach({bool disposeExtent = false}) {
    if (disposeExtent) {
      _attachedController?.extent.dispose();
    } else {
      _attachedController?.extent._currentSize.removeListener(notifyListeners);
    }
209
    _disposeAnimationControllers();
210 211
    _attachedController = null;
  }
212 213 214 215 216 217 218

  void _disposeAnimationControllers() {
    for (final AnimationController animationController in _animationControllers) {
      animationController.dispose();
    }
    _animationControllers.clear();
  }
219 220
}

221 222 223
/// A container for a [Scrollable] that responds to drag gestures by resizing
/// the scrollable until a limit is reached, and then scrolling.
///
224 225
/// {@youtube 560 315 https://www.youtube.com/watch?v=Hgw819mL_78}
///
226 227 228 229 230 231 232 233 234 235 236 237
/// This widget can be dragged along the vertical axis between its
/// [minChildSize], which defaults to `0.25` and [maxChildSize], which defaults
/// to `1.0`. These sizes are percentages of the height of the parent container.
///
/// The widget coordinates resizing and scrolling of the widget returned by
/// builder as the user drags along the horizontal axis.
///
/// The widget will initially be displayed at its initialChildSize which
/// defaults to `0.5`, meaning half the height of its parent. Dragging will work
/// between the range of minChildSize and maxChildSize (as percentages of the
/// parent container's height) as long as the builder creates a widget which
/// uses the provided [ScrollController]. If the widget created by the
238
/// [ScrollableWidgetBuilder] does not use the provided [ScrollController], the
239 240
/// sheet will remain at the initialChildSize.
///
241 242 243 244 245 246
/// By default, the widget will stay at whatever size the user drags it to. To
/// make the widget snap to specific sizes whenever they lift their finger
/// during a drag, set [snap] to `true`. The sheet will snap between
/// [minChildSize] and [maxChildSize]. Use [snapSizes] to add more sizes for
/// the sheet to snap between.
///
247 248 249 250
/// The snapping effect is only applied on user drags. Programmatically
/// manipulating the sheet size via [DraggableScrollableController.animateTo] or
/// [DraggableScrollableController.jumpTo] will ignore [snap] and [snapSizes].
///
Chris Bracken's avatar
Chris Bracken committed
251
/// By default, the widget will expand its non-occupied area to fill available
252 253 254 255
/// space in the parent. If this is not desired, e.g. because the parent wants
/// to position sheet based on the space it is taking, the [expand] property
/// may be set to false.
///
256
/// {@tool snippet}
257 258 259 260 261 262 263 264 265 266
///
/// This is a sample widget which shows a [ListView] that has 25 [ListTile]s.
/// It starts out as taking up half the body of the [Scaffold], and can be
/// dragged up to the full height of the scaffold or down to 25% of the height
/// of the scaffold. Upon reaching full height, the list contents will be
/// scrolled up or down, until they reach the top of the list again and the user
/// drags the sheet back down.
///
/// ```dart
/// class HomePage extends StatelessWidget {
267
///   const HomePage({super.key});
268
///
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
///   @override
///   Widget build(BuildContext context) {
///     return Scaffold(
///       appBar: AppBar(
///         title: const Text('DraggableScrollableSheet'),
///       ),
///       body: SizedBox.expand(
///         child: DraggableScrollableSheet(
///           builder: (BuildContext context, ScrollController scrollController) {
///             return Container(
///               color: Colors.blue[100],
///               child: ListView.builder(
///                 controller: scrollController,
///                 itemCount: 25,
///                 itemBuilder: (BuildContext context, int index) {
///                   return ListTile(title: Text('Item $index'));
///                 },
///               ),
///             );
///           },
///         ),
///       ),
///     );
///   }
/// }
/// ```
/// {@end-tool}
class DraggableScrollableSheet extends StatefulWidget {
  /// Creates a widget that can be dragged and scrolled in a single gesture.
  ///
299 300
  /// The [builder], [initialChildSize], [minChildSize], [maxChildSize] and
  /// [expand] parameters must not be null.
301
  const DraggableScrollableSheet({
302
    super.key,
303 304 305
    this.initialChildSize = 0.5,
    this.minChildSize = 0.25,
    this.maxChildSize = 1.0,
306
    this.expand = true,
307 308
    this.snap = false,
    this.snapSizes,
309
    this.snapAnimationDuration,
310
    this.controller,
311
    this.shouldCloseOnMinExtent = true,
312
    required this.builder,
313
  })  : assert(minChildSize >= 0.0),
314 315 316
        assert(maxChildSize <= 1.0),
        assert(minChildSize <= initialChildSize),
        assert(initialChildSize <= maxChildSize),
317
        assert(snapAnimationDuration == null || snapAnimationDuration > Duration.zero);
318 319 320 321

  /// The initial fractional value of the parent container's height to use when
  /// displaying the widget.
  ///
322
  /// Rebuilding the sheet with a new [initialChildSize] will only move
323 324 325
  /// the sheet to the new value if the sheet has not yet been dragged since it
  /// was first built or since the last call to [DraggableScrollableActuator.reset].
  ///
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
  /// The default value is `0.5`.
  final double initialChildSize;

  /// The minimum fractional value of the parent container's height to use when
  /// displaying the widget.
  ///
  /// The default value is `0.25`.
  final double minChildSize;

  /// The maximum fractional value of the parent container's height to use when
  /// displaying the widget.
  ///
  /// The default value is `1.0`.
  final double maxChildSize;

341 342 343 344 345 346 347 348 349 350
  /// Whether the widget should expand to fill the available space in its parent
  /// or not.
  ///
  /// In most cases, this should be true. However, in the case of a parent
  /// widget that will position this one based on its desired size (such as a
  /// [Center]), this should be set to false.
  ///
  /// The default value is true.
  final bool expand;

351 352 353 354 355 356
  /// Whether the widget should snap between [snapSizes] when the user lifts
  /// their finger during a drag.
  ///
  /// If the user's finger was still moving when they lifted it, the widget will
  /// snap to the next snap size (see [snapSizes]) in the direction of the drag.
  /// If their finger was still, the widget will snap to the nearest snap size.
357
  ///
358 359 360
  /// Snapping is not applied when the sheet is programmatically moved by
  /// calling [DraggableScrollableController.animateTo] or [DraggableScrollableController.jumpTo].
  ///
361 362 363 364
  /// Rebuilding the sheet with snap newly enabled will immediately trigger a
  /// snap unless the sheet has not yet been dragged away from
  /// [initialChildSize] since first being built or since the last call to
  /// [DraggableScrollableActuator.reset].
365 366 367 368 369 370 371 372 373 374 375 376
  final bool snap;

  /// A list of target sizes that the widget should snap to.
  ///
  /// Snap sizes are fractional values of the parent container's height. They
  /// must be listed in increasing order and be between [minChildSize] and
  /// [maxChildSize].
  ///
  /// The [minChildSize] and [maxChildSize] are implicitly included in snap
  /// sizes and do not need to be specified here. For example, `snapSizes = [.5]`
  /// will result in a sheet that snaps between [minChildSize], `.5`, and
  /// [maxChildSize].
377 378 379 380 381 382 383
  ///
  /// Any modifications to the [snapSizes] list will not take effect until the
  /// `build` function containing this widget is run again.
  ///
  /// Rebuilding with a modified or new list will trigger a snap unless the
  /// sheet has not yet been dragged away from [initialChildSize] since first
  /// being built or since the last call to [DraggableScrollableActuator.reset].
384 385
  final List<double>? snapSizes;

386 387 388 389 390 391
  /// Defines a duration for the snap animations.
  ///
  /// If it's not set, then the animation duration is the distance to the snap
  /// target divided by the velocity of the widget.
  final Duration? snapAnimationDuration;

392 393 394
  /// A controller that can be used to programmatically control this sheet.
  final DraggableScrollableController? controller;

395 396 397 398 399 400 401
  /// Whether the sheet, when dragged (or flung) to its minimum size, should
  /// cause its parent sheet to close.
  ///
  /// Set on emitted [DraggableScrollableNotification]s. It is up to parent
  /// classes to properly read and handle this value.
  final bool shouldCloseOnMinExtent;

402 403 404 405 406 407
  /// The builder that creates a child to display in this widget, which will
  /// use the provided [ScrollController] to enable dragging and scrolling
  /// of the contents.
  final ScrollableWidgetBuilder builder;

  @override
408
  State<DraggableScrollableSheet> createState() => _DraggableScrollableSheetState();
409 410
}

411 412 413 414 415 416 417
/// A [Notification] related to the extent, which is the size, and scroll
/// offset, which is the position of the child list, of the
/// [DraggableScrollableSheet].
///
/// [DraggableScrollableSheet] widgets notify their ancestors when the size of
/// the sheet changes. When the extent of the sheet changes via a drag,
/// this notification bubbles up through the tree, which means a given
Chris Bracken's avatar
Chris Bracken committed
418
/// [NotificationListener] will receive notifications for all descendant
419
/// [DraggableScrollableSheet] widgets. To focus on notifications from the
420
/// nearest [DraggableScrollableSheet] descendant, check that the [depth]
421 422 423 424 425 426 427 428 429 430 431 432 433 434
/// property of the notification is zero.
///
/// When an extent notification is received by a [NotificationListener], the
/// listener will already have completed build and layout, and it is therefore
/// too late for that widget to call [State.setState]. Any attempt to adjust the
/// build or layout based on an extent notification would result in a layout
/// that lagged one frame behind, which is a poor user experience. Extent
/// notifications are used primarily to drive animations. The [Scaffold] widget
/// listens for extent notifications and responds by driving animations for the
/// [FloatingActionButton] as the bottom sheet scrolls up.
class DraggableScrollableNotification extends Notification with ViewportNotificationMixin {
  /// Creates a notification that the extent of a [DraggableScrollableSheet] has
  /// changed.
  ///
435 436
  /// All parameters are required. The [minExtent] must be >= 0. The [maxExtent]
  /// must be <= 1.0. The [extent] must be between [minExtent] and [maxExtent].
437
  DraggableScrollableNotification({
438 439 440 441 442
    required this.extent,
    required this.minExtent,
    required this.maxExtent,
    required this.initialExtent,
    required this.context,
443
    this.shouldCloseOnMinExtent = true,
444
  }) : assert(0.0 <= minExtent),
445 446 447 448
       assert(maxExtent <= 1.0),
       assert(minExtent <= extent),
       assert(minExtent <= initialExtent),
       assert(extent <= maxExtent),
449
       assert(initialExtent <= maxExtent);
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469

  /// The current value of the extent, between [minExtent] and [maxExtent].
  final double extent;

  /// The minimum value of [extent], which is >= 0.
  final double minExtent;

  /// The maximum value of [extent].
  final double maxExtent;

  /// The initially requested value for [extent].
  final double initialExtent;

  /// The build context of the widget that fired this notification.
  ///
  /// This can be used to find the sheet's render objects to determine the size
  /// of the viewport, for instance. A listener can only assume this context
  /// is live when it first gets the notification.
  final BuildContext context;

470 471 472 473 474 475
  /// Whether the widget that fired this notification, when dragged (or flung)
  /// to minExtent, should cause its parent sheet to close.
  ///
  /// It is up to parent classes to properly read and handle this value.
  final bool shouldCloseOnMinExtent;

476 477 478 479 480 481 482
  @override
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    description.add('minExtent: $minExtent, extent: $extent, maxExtent: $maxExtent, initialExtent: $initialExtent');
  }
}

483 484 485 486 487 488 489 490 491
/// Manages state between [_DraggableScrollableSheetState],
/// [_DraggableScrollableSheetScrollController], and
/// [_DraggableScrollableSheetScrollPosition].
///
/// The State knows the pixels available along the axis the widget wants to
/// scroll, but expects to get a fraction of those pixels to render the sheet.
///
/// The ScrollPosition knows the number of pixels a user wants to move the sheet.
///
Casey Rogers's avatar
Casey Rogers committed
492
/// The [currentSize] will never be null.
493 494 495
/// The [availablePixels] will never be null, but may be `double.infinity`.
class _DraggableSheetExtent {
  _DraggableSheetExtent({
Casey Rogers's avatar
Casey Rogers committed
496 497
    required this.minSize,
    required this.maxSize,
498 499
    required this.snap,
    required this.snapSizes,
Casey Rogers's avatar
Casey Rogers committed
500
    required this.initialSize,
501
    this.snapAnimationDuration,
Casey Rogers's avatar
Casey Rogers committed
502
    ValueNotifier<double>? currentSize,
503
    bool? hasDragged,
504
    bool? hasChanged,
505
    this.shouldCloseOnMinExtent = true,
506
  })  : assert(minSize >= 0),
Casey Rogers's avatar
Casey Rogers committed
507 508 509
        assert(maxSize <= 1),
        assert(minSize <= initialSize),
        assert(initialSize <= maxSize),
510
        _currentSize = currentSize ?? ValueNotifier<double>(initialSize),
511
        availablePixels = double.infinity,
512 513
        hasDragged = hasDragged ?? false,
        hasChanged = hasChanged ?? false;
514 515

  VoidCallback? _cancelActivity;
516

Casey Rogers's avatar
Casey Rogers committed
517 518
  final double minSize;
  final double maxSize;
519 520
  final bool snap;
  final List<double> snapSizes;
521
  final Duration? snapAnimationDuration;
Casey Rogers's avatar
Casey Rogers committed
522
  final double initialSize;
523
  final bool shouldCloseOnMinExtent;
Casey Rogers's avatar
Casey Rogers committed
524
  final ValueNotifier<double> _currentSize;
525 526
  double availablePixels;

527
  // Used to disable snapping until the user has dragged on the sheet.
528
  bool hasDragged;
529

530 531 532 533 534 535 536 537 538 539 540
  // Used to determine if the sheet should move to a new initial size when it
  // changes.
  // We need both `hasChanged` and `hasDragged` to achieve the following
  // behavior:
  //   1. The sheet should only snap following user drags (as opposed to
  //      programmatic sheet changes). See docs for `animateTo` and `jumpTo`.
  //   2. The sheet should move to a new initial child size on rebuild iff the
  //      sheet has not changed, either by drag or programmatic control. See
  //      docs for `initialChildSize`.
  bool hasChanged;

Casey Rogers's avatar
Casey Rogers committed
541 542
  bool get isAtMin => minSize >= _currentSize.value;
  bool get isAtMax => maxSize <= _currentSize.value;
543

Casey Rogers's avatar
Casey Rogers committed
544 545
  double get currentSize => _currentSize.value;
  double get currentPixels => sizeToPixels(_currentSize.value);
546

Casey Rogers's avatar
Casey Rogers committed
547
  List<double> get pixelSnapSizes => snapSizes.map(sizeToPixels).toList();
548

549 550 551
  /// Start an activity that affects the sheet and register a cancel call back
  /// that will be called if another activity starts.
  ///
552 553
  /// The `onCanceled` callback will get called even if the subsequent activity
  /// started after this one finished, so `onCanceled` must be safe to call at
554 555 556 557 558 559
  /// any time.
  void startActivity({required VoidCallback onCanceled}) {
    _cancelActivity?.call();
    _cancelActivity = onCanceled;
  }

Casey Rogers's avatar
Casey Rogers committed
560
  /// The scroll position gets inputs in terms of pixels, but the size is
561
  /// expected to be expressed as a number between 0..1.
562 563 564
  ///
  /// This should only be called to respond to a user drag. To update the
  /// size in response to a programmatic call, use [updateSize] directly.
565
  void addPixelDelta(double delta, BuildContext context) {
566 567 568 569 570 571
    // Stop any playing sheet animations.
    _cancelActivity?.call();
    _cancelActivity = null;
    // The user has interacted with the sheet, set `hasDragged` to true so that
    // we'll snap if applicable.
    hasDragged = true;
572
    hasChanged = true;
573 574 575
    if (availablePixels == 0) {
      return;
    }
Casey Rogers's avatar
Casey Rogers committed
576
    updateSize(currentSize + pixelsToSize(delta), context);
577 578
  }

579 580 581 582 583
  /// Set the size to the new value. [newSize] should be a number between
  /// [minSize] and [maxSize].
  ///
  /// This can be triggered by a programmatic (e.g. controller triggered) change
  /// or a user drag.
Casey Rogers's avatar
Casey Rogers committed
584
  void updateSize(double newSize, BuildContext context) {
585 586 587 588 589
    final double clampedSize = clampDouble(newSize, minSize, maxSize);
    if (_currentSize.value == clampedSize) {
      return;
    }
    _currentSize.value = clampedSize;
590
    DraggableScrollableNotification(
Casey Rogers's avatar
Casey Rogers committed
591 592 593 594
      minExtent: minSize,
      maxExtent: maxSize,
      extent: currentSize,
      initialExtent: initialSize,
595
      context: context,
596
      shouldCloseOnMinExtent: shouldCloseOnMinExtent,
597
    ).dispatch(context);
598
  }
599

Casey Rogers's avatar
Casey Rogers committed
600 601
  double pixelsToSize(double pixels) {
    return pixels / availablePixels * maxSize;
602 603
  }

604 605
  double sizeToPixels(double size) {
    return size / maxSize * availablePixels;
606
  }
607

xubaolin's avatar
xubaolin committed
608 609 610 611
  void dispose() {
    _currentSize.dispose();
  }

612
  _DraggableSheetExtent copyWith({
Casey Rogers's avatar
Casey Rogers committed
613 614
    required double minSize,
    required double maxSize,
615 616
    required bool snap,
    required List<double> snapSizes,
Casey Rogers's avatar
Casey Rogers committed
617
    required double initialSize,
618
    Duration? snapAnimationDuration,
619
    bool shouldCloseOnMinExtent = true,
620 621
  }) {
    return _DraggableSheetExtent(
Casey Rogers's avatar
Casey Rogers committed
622 623
      minSize: minSize,
      maxSize: maxSize,
624 625
      snap: snap,
      snapSizes: snapSizes,
626
      snapAnimationDuration: snapAnimationDuration,
Casey Rogers's avatar
Casey Rogers committed
627
      initialSize: initialSize,
628 629 630
      // Set the current size to the possibly updated initial size if the sheet
      // hasn't changed yet.
      currentSize: ValueNotifier<double>(hasChanged
631
          ? clampDouble(_currentSize.value, minSize, maxSize)
Casey Rogers's avatar
Casey Rogers committed
632
          : initialSize),
633
      hasDragged: hasDragged,
634
      hasChanged: hasChanged,
635
      shouldCloseOnMinExtent: shouldCloseOnMinExtent,
636 637
    );
  }
638 639 640
}

class _DraggableScrollableSheetState extends State<DraggableScrollableSheet> {
641 642
  late _DraggableScrollableSheetScrollController _scrollController;
  late _DraggableSheetExtent _extent;
643 644 645 646

  @override
  void initState() {
    super.initState();
647
    _extent = _DraggableSheetExtent(
Casey Rogers's avatar
Casey Rogers committed
648 649
      minSize: widget.minChildSize,
      maxSize: widget.maxChildSize,
650 651
      snap: widget.snap,
      snapSizes: _impliedSnapSizes(),
652
      snapAnimationDuration: widget.snapAnimationDuration,
Casey Rogers's avatar
Casey Rogers committed
653
      initialSize: widget.initialChildSize,
654
      shouldCloseOnMinExtent: widget.shouldCloseOnMinExtent,
655 656
    );
    _scrollController = _DraggableScrollableSheetScrollController(extent: _extent);
657
    widget.controller?._attach(_scrollController);
658 659
  }

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
  List<double> _impliedSnapSizes() {
    for (int index = 0; index < (widget.snapSizes?.length ?? 0); index += 1) {
      final double snapSize = widget.snapSizes![index];
      assert(snapSize >= widget.minChildSize && snapSize <= widget.maxChildSize,
        '${_snapSizeErrorMessage(index)}\nSnap sizes must be between `minChildSize` and `maxChildSize`. ');
      assert(index == 0 || snapSize > widget.snapSizes![index - 1],
        '${_snapSizeErrorMessage(index)}\nSnap sizes must be in ascending order. ');
    }
    // Ensure the snap sizes start and end with the min and max child sizes.
    if (widget.snapSizes == null || widget.snapSizes!.isEmpty) {
      return <double>[
        widget.minChildSize,
        widget.maxChildSize,
      ];
    }
    return <double>[
      if (widget.snapSizes!.first != widget.minChildSize) widget.minChildSize,
      ...widget.snapSizes!,
      if (widget.snapSizes!.last != widget.maxChildSize) widget.maxChildSize,
    ];
  }

682 683 684
  @override
  void didUpdateWidget(covariant DraggableScrollableSheet oldWidget) {
    super.didUpdateWidget(oldWidget);
xubaolin's avatar
xubaolin committed
685 686 687 688
    if (widget.controller != oldWidget.controller) {
      oldWidget.controller?._detach();
      widget.controller?._attach(_scrollController);
    }
689
    _replaceExtent(oldWidget);
690 691
  }

692 693 694 695
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (_InheritedResetNotifier.shouldReset(context)) {
696
      _scrollController.reset();
697 698 699
    }
  }

700 701
  @override
  Widget build(BuildContext context) {
702 703 704 705 706 707 708 709 710 711 712 713 714 715
    return ValueListenableBuilder<double>(
      valueListenable: _extent._currentSize,
      builder: (BuildContext context, double currentSize, Widget? child) => LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          _extent.availablePixels = widget.maxChildSize * constraints.biggest.height;
          final Widget sheet = FractionallySizedBox(
            heightFactor: currentSize,
            alignment: Alignment.bottomCenter,
            child: child,
          );
          return widget.expand ? SizedBox.expand(child: sheet) : sheet;
        },
      ),
      child: widget.builder(context, _scrollController),
716 717 718 719 720
    );
  }

  @override
  void dispose() {
xubaolin's avatar
xubaolin committed
721
    widget.controller?._detach(disposeExtent: true);
722 723 724
    _scrollController.dispose();
    super.dispose();
  }
725

726
  void _replaceExtent(covariant DraggableScrollableSheet oldWidget) {
727
    final _DraggableSheetExtent previousExtent = _extent;
xubaolin's avatar
xubaolin committed
728
    _extent = previousExtent.copyWith(
Casey Rogers's avatar
Casey Rogers committed
729 730
      minSize: widget.minChildSize,
      maxSize: widget.maxChildSize,
731 732
      snap: widget.snap,
      snapSizes: _impliedSnapSizes(),
733
      snapAnimationDuration: widget.snapAnimationDuration,
Casey Rogers's avatar
Casey Rogers committed
734
      initialSize: widget.initialChildSize,
735 736 737 738
    );
    // Modify the existing scroll controller instead of replacing it so that
    // developers listening to the controller do not have to rebuild their listeners.
    _scrollController.extent = _extent;
739 740
    // If an external facing controller was provided, let it know that the
    // extent has been replaced.
741
    widget.controller?._onExtentReplaced(previousExtent);
xubaolin's avatar
xubaolin committed
742
    previousExtent.dispose();
743 744 745 746 747 748 749 750 751
    if (widget.snap
        && (widget.snap != oldWidget.snap || widget.snapSizes != oldWidget.snapSizes)
        && _scrollController.hasClients
    ) {
      // Trigger a snap in case snap or snapSizes has changed and there is a
      // scroll position currently attached. We put this in a post frame
      // callback so that `build` can update `_extent.availablePixels` before
      // this runs-we can't use the previous extent's available pixels as it may
      // have changed when the widget was updated.
752
      WidgetsBinding.instance.addPostFrameCallback((Duration timeStamp) {
753 754 755 756 757
        for (int index = 0; index < _scrollController.positions.length; index++) {
          final _DraggableScrollableSheetScrollPosition position =
            _scrollController.positions.elementAt(index) as _DraggableScrollableSheetScrollPosition;
          position.goBallistic(0);
        }
758 759 760 761
      });
    }
  }

762 763
  String _snapSizeErrorMessage(int invalidIndex) {
    final List<String> snapSizesWithIndicator = widget.snapSizes!.asMap().keys.map(
764
      (int index) {
765 766 767 768 769 770 771 772 773 774
        final String snapSizeString = widget.snapSizes![index].toString();
        if (index == invalidIndex) {
          return '>>> $snapSizeString <<<';
        }
        return snapSizeString;
      },
    ).toList();
    return "Invalid snapSize '${widget.snapSizes![invalidIndex]}' at index $invalidIndex of:\n"
        '  $snapSizesWithIndicator';
  }
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
}

/// A [ScrollController] suitable for use in a [ScrollableWidgetBuilder] created
/// by a [DraggableScrollableSheet].
///
/// If a [DraggableScrollableSheet] contains content that is exceeds the height
/// of its container, this controller will allow the sheet to both be dragged to
/// fill the container and then scroll the child content.
///
/// See also:
///
///  * [_DraggableScrollableSheetScrollPosition], which manages the positioning logic for
///    this controller.
///  * [PrimaryScrollController], which can be used to establish a
///    [_DraggableScrollableSheetScrollController] as the primary controller for
///    descendants.
class _DraggableScrollableSheetScrollController extends ScrollController {
  _DraggableScrollableSheetScrollController({
793
    required this.extent,
794
  });
795

796
  _DraggableSheetExtent extent;
797
  VoidCallback? onPositionDetached;
798 799 800 801 802

  @override
  _DraggableScrollableSheetScrollPosition createScrollPosition(
    ScrollPhysics physics,
    ScrollContext context,
803
    ScrollPosition? oldPosition,
804 805
  ) {
    return _DraggableScrollableSheetScrollPosition(
806
      physics: physics.applyTo(const AlwaysScrollableScrollPhysics()),
807 808
      context: context,
      oldPosition: oldPosition,
809
      getExtent: () => extent,
810 811 812 813 814 815 816 817
    );
  }

  @override
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    description.add('extent: $extent');
  }
818 819 820 821

  @override
  _DraggableScrollableSheetScrollPosition get position =>
      super.position as _DraggableScrollableSheetScrollPosition;
822 823 824 825

  void reset() {
    extent._cancelActivity?.call();
    extent.hasDragged = false;
826
    extent.hasChanged = false;
827 828 829 830 831 832 833 834 835 836 837 838
    // jumpTo can result in trying to replace semantics during build.
    // Just animate really fast.
    // Avoid doing it at all if the offset is already 0.0.
    if (offset != 0.0) {
      animateTo(
        0.0,
        duration: const Duration(milliseconds: 1),
        curve: Curves.linear,
      );
    }
    extent.updateSize(extent.initialSize, position.context.notificationContext!);
  }
839 840 841 842 843 844

  @override
  void detach(ScrollPosition position) {
    onPositionDetached?.call();
    super.detach(position);
  }
845 846 847 848 849 850 851 852
}

/// A scroll position that manages scroll activities for
/// [_DraggableScrollableSheetScrollController].
///
/// This class is a concrete subclass of [ScrollPosition] logic that handles a
/// single [ScrollContext], such as a [Scrollable]. An instance of this class
/// manages [ScrollActivity] instances, which changes the
Casey Rogers's avatar
Casey Rogers committed
853
/// [_DraggableSheetExtent.currentSize] or visible content offset in the
854 855 856 857 858
/// [Scrollable]'s [Viewport]
///
/// See also:
///
///  * [_DraggableScrollableSheetScrollController], which uses this as its [ScrollPosition].
859
class _DraggableScrollableSheetScrollPosition extends ScrollPositionWithSingleContext {
860
  _DraggableScrollableSheetScrollPosition({
861 862 863
    required super.physics,
    required super.context,
    super.oldPosition,
864
    required this.getExtent,
865
  });
866

867
  VoidCallback? _dragCancelCallback;
868
  final _DraggableSheetExtent Function() getExtent;
869
  final Set<AnimationController> _ballisticControllers = <AnimationController>{};
870 871
  bool get listShouldScroll => pixels > 0.0;

872 873
  _DraggableSheetExtent get extent => getExtent();

874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
  @override
  void absorb(ScrollPosition other) {
    super.absorb(other);
    assert(_dragCancelCallback == null);

    if (other is! _DraggableScrollableSheetScrollPosition) {
      return;
    }

    if (other._dragCancelCallback != null) {
      _dragCancelCallback = other._dragCancelCallback;
      other._dragCancelCallback = null;
    }
  }

889 890
  @override
  void beginActivity(ScrollActivity? newActivity) {
891 892 893 894
    // Cancel the running ballistic simulations
    for (final AnimationController ballisticController in _ballisticControllers) {
      ballisticController.stop();
    }
895 896 897
    super.beginActivity(newActivity);
  }

898 899 900
  @override
  void applyUserOffset(double delta) {
    if (!listShouldScroll &&
901 902 903
        (!(extent.isAtMin || extent.isAtMax) ||
          (extent.isAtMin && delta < 0) ||
          (extent.isAtMax && delta > 0))) {
904
      extent.addPixelDelta(-delta, context.notificationContext!);
905 906 907 908 909
    } else {
      super.applyUserOffset(delta);
    }
  }

910 911 912
  bool get _isAtSnapSize {
    return extent.snapSizes.any(
      (double snapSize) {
913
        return (extent.currentSize - snapSize).abs() <= extent.pixelsToSize(physics.toleranceFor(this).distance);
914 915 916
      },
    );
  }
917
  bool get _shouldSnap => extent.snap && extent.hasDragged && !_isAtSnapSize;
918

919 920
  @override
  void dispose() {
921 922 923 924
    for (final AnimationController ballisticController in _ballisticControllers) {
      ballisticController.dispose();
    }
    _ballisticControllers.clear();
925 926 927
    super.dispose();
  }

928 929
  @override
  void goBallistic(double velocity) {
930 931 932
    if ((velocity == 0.0 && !_shouldSnap) ||
        (velocity < 0.0 && listShouldScroll) ||
        (velocity > 0.0 && extent.isAtMax)) {
933 934 935 936 937 938 939
      super.goBallistic(velocity);
      return;
    }
    // Scrollable expects that we will dispose of its current _dragCancelCallback
    _dragCancelCallback?.call();
    _dragCancelCallback = null;

940 941 942 943
    late final Simulation simulation;
    if (extent.snap) {
      // Snap is enabled, simulate snapping instead of clamping scroll.
      simulation = _SnappingSimulation(
944 945 946
        position: extent.currentPixels,
        initialVelocity: velocity,
        pixelSnapSize: extent.pixelSnapSizes,
947
        snapAnimationDuration: extent.snapAnimationDuration,
948
        tolerance: physics.toleranceFor(this),
949
      );
950 951 952 953 954 955 956
    } else {
      // The iOS bouncing simulation just isn't right here - once we delegate
      // the ballistic back to the ScrollView, it will use the right simulation.
      simulation = ClampingScrollSimulation(
        // Run the simulation in terms of pixels, not extent.
        position: extent.currentPixels,
        velocity: velocity,
957
        tolerance: physics.toleranceFor(this),
958 959
      );
    }
960 961

    final AnimationController ballisticController = AnimationController.unbounded(
962
      debugLabel: objectRuntimeType(this, '_DraggableScrollableSheetPosition'),
963 964
      vsync: context.vsync,
    );
965 966
    _ballisticControllers.add(ballisticController);

967
    double lastPosition = extent.currentPixels;
968
    void tick() {
969 970
      final double delta = ballisticController.value - lastPosition;
      lastPosition = ballisticController.value;
971
      extent.addPixelDelta(delta, context.notificationContext!);
972 973 974 975
      if ((velocity > 0 && extent.isAtMax) || (velocity < 0 && extent.isAtMin)) {
        // Make sure we pass along enough velocity to keep scrolling - otherwise
        // we just "bounce" off the top making it look like the list doesn't
        // have more to scroll.
976
        velocity = ballisticController.velocity + (physics.toleranceFor(this).velocity * ballisticController.velocity.sign);
977 978
        super.goBallistic(velocity);
        ballisticController.stop();
979 980
      } else if (ballisticController.isCompleted) {
        super.goBallistic(0);
981 982 983 984
      }
    }

    ballisticController
985
      ..addListener(tick)
986
      ..animateWith(simulation).whenCompleteOrCancel(
987
        () {
988 989 990 991
          if (_ballisticControllers.contains(ballisticController)) {
            _ballisticControllers.remove(ballisticController);
            ballisticController.dispose();
          }
992
        },
993 994 995 996 997 998 999 1000 1001 1002
      );
  }

  @override
  Drag drag(DragStartDetails details, VoidCallback dragCancelCallback) {
    // Save this so we can call it later if we have to [goBallistic] on our own.
    _dragCancelCallback = dragCancelCallback;
    return super.drag(details, dragCancelCallback);
  }
}
1003 1004 1005 1006

/// A widget that can notify a descendent [DraggableScrollableSheet] that it
/// should reset its position to the initial state.
///
1007
/// The [Scaffold] uses this widget to notify a persistent bottom sheet that
1008 1009 1010
/// the user has tapped back if the sheet has started to cover more of the body
/// than when at its initial position. This is important for users of assistive
/// technology, where dragging may be difficult to communicate.
1011 1012 1013 1014 1015 1016 1017
///
/// This is just a wrapper on top of [DraggableScrollableController]. It is
/// primarily useful for controlling a sheet in a part of the widget tree that
/// the current code does not control (e.g. library code trying to affect a sheet
/// in library users' code). Generally, it's easier to control the sheet
/// directly by creating a controller and passing the controller to the sheet in
/// its constructor (see [DraggableScrollableSheet.controller]).
1018 1019 1020 1021 1022 1023
class DraggableScrollableActuator extends StatelessWidget {
  /// Creates a widget that can notify descendent [DraggableScrollableSheet]s
  /// to reset to their initial position.
  ///
  /// The [child] parameter is required.
  DraggableScrollableActuator({
1024
    super.key,
1025
    required this.child,
1026
  });
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042

  /// This child's [DraggableScrollableSheet] descendant will be reset when the
  /// [reset] method is applied to a context that includes it.
  ///
  /// Must not be null.
  final Widget child;

  final _ResetNotifier _notifier = _ResetNotifier();

  /// Notifies any descendant [DraggableScrollableSheet] that it should reset
  /// to its initial position.
  ///
  /// Returns `true` if a [DraggableScrollableActuator] is available and
  /// some [DraggableScrollableSheet] is listening for updates, `false`
  /// otherwise.
  static bool reset(BuildContext context) {
1043
    final _InheritedResetNotifier? notifier = context.dependOnInheritedWidgetOfExactType<_InheritedResetNotifier>();
1044 1045 1046 1047 1048 1049 1050 1051
    if (notifier == null) {
      return false;
    }
    return notifier._sendReset();
  }

  @override
  Widget build(BuildContext context) {
1052
    return _InheritedResetNotifier(notifier: _notifier, child: child);
1053 1054 1055
  }
}

1056
/// A [ChangeNotifier] to use with [InheritedResetNotifier] to notify
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
/// descendants that they should reset to initial state.
class _ResetNotifier extends ChangeNotifier {
  /// Whether someone called [sendReset] or not.
  ///
  /// This flag should be reset after checking it.
  bool _wasCalled = false;

  /// Fires a reset notification to descendants.
  ///
  /// Returns false if there are no listeners.
  bool sendReset() {
    if (!hasListeners) {
      return false;
    }
    _wasCalled = true;
    notifyListeners();
    return true;
  }
}

class _InheritedResetNotifier extends InheritedNotifier<_ResetNotifier> {
  /// Creates an [InheritedNotifier] that the [DraggableScrollableSheet] will
Casey Rogers's avatar
Casey Rogers committed
1079
  /// listen to for an indication that it should reset itself back to [DraggableScrollableSheet.initialChildSize].
1080 1081 1082
  ///
  /// The [child] and [notifier] properties must not be null.
  const _InheritedResetNotifier({
1083 1084 1085
    required super.child,
    required _ResetNotifier super.notifier,
  });
1086

1087
  bool _sendReset() => notifier!.sendReset();
1088 1089 1090 1091 1092 1093

  /// Specifies whether the [DraggableScrollableSheet] should reset to its
  /// initial position.
  ///
  /// Returns true if the notifier requested a reset, false otherwise.
  static bool shouldReset(BuildContext context) {
1094
    final InheritedWidget? widget = context.dependOnInheritedWidgetOfExactType<_InheritedResetNotifier>();
1095 1096 1097 1098
    if (widget == null) {
      return false;
    }
    assert(widget is _InheritedResetNotifier);
1099
    final _InheritedResetNotifier inheritedNotifier = widget as _InheritedResetNotifier;
1100 1101
    final bool wasCalled = inheritedNotifier.notifier!._wasCalled;
    inheritedNotifier.notifier!._wasCalled = false;
1102 1103 1104
    return wasCalled;
  }
}
1105 1106 1107 1108 1109 1110

class _SnappingSimulation extends Simulation {
  _SnappingSimulation({
    required this.position,
    required double initialVelocity,
    required List<double> pixelSnapSize,
1111
    Duration? snapAnimationDuration,
1112 1113
    super.tolerance,
  }) {
1114
    _pixelSnapSize = _getSnapSize(initialVelocity, pixelSnapSize);
1115 1116 1117 1118

    if (snapAnimationDuration != null && snapAnimationDuration.inMilliseconds > 0) {
       velocity = (_pixelSnapSize - position) * 1000 / snapAnimationDuration.inMilliseconds;
    }
1119 1120
    // Check the direction of the target instead of the sign of the velocity because
    // we may snap in the opposite direction of velocity if velocity is very low.
1121
    else if (_pixelSnapSize < position) {
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
      velocity = math.min(-minimumSpeed, initialVelocity);
    } else {
      velocity = math.max(minimumSpeed, initialVelocity);
    }
  }

  final double position;
  late final double velocity;

  // A minimum speed to snap at. Used to ensure that the snapping animation
  // does not play too slowly.
  static const double minimumSpeed = 1600.0;

  late final double _pixelSnapSize;

  @override
  double dx(double time) {
    if (isDone(time)) {
      return 0;
    }
    return velocity;
  }

  @override
  bool isDone(double time) {
    return x(time) == _pixelSnapSize;
  }

  @override
  double x(double time) {
    final double newPosition = position + velocity * time;
    if ((velocity >= 0 && newPosition > _pixelSnapSize) ||
        (velocity < 0 && newPosition < _pixelSnapSize)) {
      // We're passed the snap size, return it instead.
      return _pixelSnapSize;
    }
    return newPosition;
  }

  // Find the two closest snap sizes to the position. If the velocity is
  // non-zero, select the size in the velocity's direction. Otherwise,
  // the nearest snap size.
  double _getSnapSize(double initialVelocity, List<double> pixelSnapSizes) {
    final int indexOfNextSize = pixelSnapSizes
        .indexWhere((double size) => size >= position);
    if (indexOfNextSize == 0) {
      return pixelSnapSizes.first;
    }
    final double nextSize = pixelSnapSizes[indexOfNextSize];
    final double previousSize = pixelSnapSizes[indexOfNextSize - 1];
    if (initialVelocity.abs() <= tolerance.velocity) {
      // If velocity is zero, snap to the nearest snap size with the minimum velocity.
      if (position - previousSize < nextSize - position) {
        return previousSize;
      } else {
        return nextSize;
      }
    }
    // Snap forward or backward depending on current velocity.
    if (initialVelocity < 0.0) {
      return pixelSnapSizes[indexOfNextSize - 1];
    }
    return pixelSnapSizes[indexOfNextSize];
  }
}