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

import 'dart:math' as math;

7
import 'package:flutter/foundation.dart';
8 9 10 11 12 13 14 15
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';

import 'basic.dart';
import 'framework.dart';
import 'primary_scroll_controller.dart';
import 'scroll_activity.dart';
16
import 'scroll_configuration.dart';
17 18 19 20 21 22
import 'scroll_context.dart';
import 'scroll_controller.dart';
import 'scroll_metrics.dart';
import 'scroll_physics.dart';
import 'scroll_position.dart';
import 'scroll_view.dart';
23
import 'sliver_fill.dart';
24 25
import 'viewport.dart';

26
/// Signature used by [NestedScrollView] for building its header.
27 28 29 30 31
///
/// The `innerBoxIsScrolled` argument is typically used to control the
/// [SliverAppBar.forceElevated] property to ensure that the app bar shows a
/// shadow, since it would otherwise not necessarily be aware that it had
/// content ostensibly below it.
32
typedef NestedScrollViewHeaderSliversBuilder = List<Widget> Function(BuildContext context, bool innerBoxIsScrolled);
33

34 35 36 37
/// A scrolling view inside of which can be nested other scrolling views, with
/// their scroll positions being intrinsically linked.
///
/// The most common use case for this widget is a scrollable view with a
38
/// flexible [SliverAppBar] containing a [TabBar] in the header (built by
39 40 41 42 43 44 45 46 47 48
/// [headerSliverBuilder], and with a [TabBarView] in the [body], such that the
/// scrollable view's contents vary based on which tab is visible.
///
/// ## Motivation
///
/// In a normal [ScrollView], there is one set of slivers (the components of the
/// scrolling view). If one of those slivers hosted a [TabBarView] which scrolls
/// in the opposite direction (e.g. allowing the user to swipe horizontally
/// between the pages represented by the tabs, while the list scrolls
/// vertically), then any list inside that [TabBarView] would not interact with
49
/// the outer [ScrollView]. For example, flinging the inner list to scroll to
50 51 52 53 54 55 56 57
/// the top would not cause a collapsed [SliverAppBar] in the outer [ScrollView]
/// to expand.
///
/// [NestedScrollView] solves this problem by providing custom
/// [ScrollController]s for the outer [ScrollView] and the inner [ScrollView]s
/// (those inside the [TabBarView], hooking them together so that they appear,
/// to the user, as one coherent scroll view.
///
58
/// {@tool sample --template=stateless_widget_material}
59 60 61 62 63 64 65 66 67 68
///
/// This example shows a [NestedScrollView] whose header is the combination of a
/// [TabBar] in a [SliverAppBar] and whose body is a [TabBarView]. It uses a
/// [SliverOverlapAbsorber]/[SliverOverlapInjector] pair to make the inner lists
/// align correctly, and it uses [SafeArea] to avoid any horizontal disturbances
/// (e.g. the "notch" on iOS when the phone is horizontal). In addition,
/// [PageStorageKey]s are used to remember the scroll position of each tab's
/// list.
///
/// ```dart
69
/// Widget build(BuildContext context) {
70
///   final List<String> _tabs = <String>['Tab 1', 'Tab 2'];
71 72
///   return DefaultTabController(
///     length: _tabs.length, // This is the number of tabs.
Kate Lovett's avatar
Kate Lovett committed
73 74 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
///     child: Scaffold(
///       body: NestedScrollView(
///         headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
///           // These are the slivers that show up in the "outer" scroll view.
///           return <Widget>[
///             SliverOverlapAbsorber(
///               // This widget takes the overlapping behavior of the SliverAppBar,
///               // and redirects it to the SliverOverlapInjector below. If it is
///               // missing, then it is possible for the nested "inner" scroll view
///               // below to end up under the SliverAppBar even when the inner
///               // scroll view thinks it has not been scrolled.
///               // This is not necessary if the "headerSliverBuilder" only builds
///               // widgets that do not overlap the next sliver.
///               handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
///               sliver: SliverAppBar(
///                 title: const Text('Books'), // This is the title in the app bar.
///                 pinned: true,
///                 expandedHeight: 150.0,
///                 // The "forceElevated" property causes the SliverAppBar to show
///                 // a shadow. The "innerBoxIsScrolled" parameter is true when the
///                 // inner scroll view is scrolled beyond its "zero" point, i.e.
///                 // when it appears to be scrolled below the SliverAppBar.
///                 // Without this, there are cases where the shadow would appear
///                 // or not appear inappropriately, because the SliverAppBar is
///                 // not actually aware of the precise position of the inner
///                 // scroll views.
///                 forceElevated: innerBoxIsScrolled,
///                 bottom: TabBar(
///                   // These are the widgets to put in each tab in the tab bar.
///                   tabs: _tabs.map((String name) => Tab(text: name)).toList(),
///                 ),
104
///               ),
105
///             ),
Kate Lovett's avatar
Kate Lovett committed
106 107 108 109 110 111 112 113 114 115 116 117 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 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
///           ];
///         },
///         body: TabBarView(
///           // These are the contents of the tab views, below the tabs.
///           children: _tabs.map((String name) {
///             return SafeArea(
///               top: false,
///               bottom: false,
///               child: Builder(
///                 // This Builder is needed to provide a BuildContext that is
///                 // "inside" the NestedScrollView, so that
///                 // sliverOverlapAbsorberHandleFor() can find the
///                 // NestedScrollView.
///                 builder: (BuildContext context) {
///                   return CustomScrollView(
///                     // The "controller" and "primary" members should be left
///                     // unset, so that the NestedScrollView can control this
///                     // inner scroll view.
///                     // If the "controller" property is set, then this scroll
///                     // view will not be associated with the NestedScrollView.
///                     // The PageStorageKey should be unique to this ScrollView;
///                     // it allows the list to remember its scroll position when
///                     // the tab view is not on the screen.
///                     key: PageStorageKey<String>(name),
///                     slivers: <Widget>[
///                       SliverOverlapInjector(
///                         // This is the flip side of the SliverOverlapAbsorber
///                         // above.
///                         handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
///                       ),
///                       SliverPadding(
///                         padding: const EdgeInsets.all(8.0),
///                         // In this example, the inner scroll view has
///                         // fixed-height list items, hence the use of
///                         // SliverFixedExtentList. However, one could use any
///                         // sliver widget here, e.g. SliverList or SliverGrid.
///                         sliver: SliverFixedExtentList(
///                           // The items in this example are fixed to 48 pixels
///                           // high. This matches the Material Design spec for
///                           // ListTile widgets.
///                           itemExtent: 48.0,
///                           delegate: SliverChildBuilderDelegate(
///                             (BuildContext context, int index) {
///                               // This builder is called for each child.
///                               // In this example, we just number each list item.
///                               return ListTile(
///                                 title: Text('Item $index'),
///                               );
///                             },
///                             // The childCount of the SliverChildBuilderDelegate
///                             // specifies how many children this inner list
///                             // has. In this example, each tab has a list of
///                             // exactly 30 items, but this is arbitrary.
///                             childCount: 30,
///                           ),
161
///                         ),
162
///                       ),
Kate Lovett's avatar
Kate Lovett committed
163 164 165 166 167 168 169
///                     ],
///                   );
///                 },
///               ),
///             );
///           }).toList(),
///         ),
170
///       ),
171
///     ),
172 173
///   );
/// }
174
/// ```
175
/// {@end-tool}
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
///
/// ## [SliverAppBar]s with [NestedScrollView]s
///
/// Using a [SliverAppBar] in the outer scroll view, or [headerSliverBuilder],
/// of a [NestedScrollView] may require special configurations in order to work
/// as it would if the outer and inner were one single scroll view, like a
/// [CustomScrollView].
///
/// ### Pinned [SliverAppBar]s
///
/// A pinned [SliverAppBar] works in a [NestedScrollView] exactly as it would in
/// another scroll view, like [CustomScrollView]. When using
/// [SliverAppBar.pinned], the app bar remains visible at the top of the scroll
/// view. The app bar can still expand and contract as the user scrolls, but it
/// will remain visible rather than being scrolled out of view.
///
192
/// This works naturally in a [NestedScrollView], as the pinned [SliverAppBar]
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
/// is not expected to move in or out of the visible portion of the viewport.
/// As the inner or outer [Scrollable]s are moved, the app bar persists as
/// expected.
///
/// If the app bar is floating, pinned, and using an expanded height, follow the
/// floating convention laid out below.
///
/// ### Floating [SliverAppBar]s
///
/// When placed in the outer scrollable, or the [headerSliverBuilder],
/// a [SliverAppBar] that floats, using [SliverAppBar.floating] will not be
/// triggered to float over the inner scroll view, or [body], automatically.
///
/// This is because a floating app bar uses the scroll offset of its own
/// [Scrollable] to dictate the floating action. Being two separate inner and
/// outer [Scrollable]s, a [SliverAppBar] in the outer header is not aware of
/// changes in the scroll offset of the inner body.
///
/// In order to float the outer, use [NestedScrollView.floatHeaderSlivers]. When
/// set to true, the nested scrolling coordinator will prioritize floating in
/// the header slivers before applying the remaining drag to the body.
///
/// Furthermore, the `floatHeaderSlivers` flag should also be used when using an
/// app bar that is floating, pinned, and has an expanded height. In this
/// configuration, the flexible space of the app bar will open and collapse,
/// while the primary portion of the app bar remains pinned.
///
220
/// {@tool sample --template=stateless_widget_material}
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
///
/// This simple example shows a [NestedScrollView] whose header contains a
/// floating [SliverAppBar]. By using the [floatHeaderSlivers] property, the
/// floating behavior is coordinated between the outer and inner [Scrollable]s,
/// so it behaves as it would in a single scrollable.
///
/// ```dart
/// Widget build(BuildContext context) {
///   return Scaffold(
///     body: NestedScrollView(
///       // Setting floatHeaderSlivers to true is required in order to float
///       // the outer slivers over the inner scrollable.
///       floatHeaderSlivers: true,
///       headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
///         return <Widget>[
///           SliverAppBar(
///             title: const Text('Floating Nested SliverAppBar'),
///             floating: true,
///             expandedHeight: 200.0,
///             forceElevated: innerBoxIsScrolled,
///           ),
///         ];
///       },
///       body: ListView.builder(
///         padding: const EdgeInsets.all(8),
///         itemCount: 30,
///         itemBuilder: (BuildContext context, int index) {
248
///           return SizedBox(
249 250 251 252 253 254 255 256 257 258 259 260 261
///             height: 50,
///             child: Center(child: Text('Item $index')),
///           );
///         }
///       )
///     )
///   );
/// }
/// ```
/// {@end-tool}
///
/// ### Snapping [SliverAppBar]s
///
262
/// Floating [SliverAppBar]s also have the option to perform a snapping animation.
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
/// If [SliverAppBar.snap] is true, then a scroll that exposes the floating app
/// bar will trigger an animation that slides the entire app bar into view.
/// Similarly if a scroll dismisses the app bar, the animation will slide the
/// app bar completely out of view.
///
/// It is possible with a [NestedScrollView] to perform just the snapping
/// animation without floating the app bar in and out. By not using the
/// [NestedScrollView.floatHeaderSlivers], the app bar will snap in and out
/// without floating.
///
/// The [SliverAppBar.snap] animation should be used in conjunction with the
/// [SliverOverlapAbsorber] and  [SliverOverlapInjector] widgets when
/// implemented in a [NestedScrollView]. These widgets take any overlapping
/// behavior of the [SliverAppBar] in the header and redirect it to the
/// [SliverOverlapInjector] in the body. If it is missing, then it is possible
/// for the nested "inner" scroll view below to end up under the [SliverAppBar]
/// even when the inner scroll view thinks it has not been scrolled.
///
281
/// {@tool sample --template=stateless_widget_material}
282 283 284
///
/// This simple example shows a [NestedScrollView] whose header contains a
/// snapping, floating [SliverAppBar]. _Without_ setting any additional flags,
285 286 287 288
/// e.g [NestedScrollView.floatHeaderSlivers], the [SliverAppBar] will animate
/// in and out without floating. The [SliverOverlapAbsorber] and
/// [SliverOverlapInjector] maintain the proper alignment between the two
/// separate scroll views.
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 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
///
/// ```dart
/// Widget build(BuildContext context) {
///   return Scaffold(
///     body: NestedScrollView(
///       headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
///         return <Widget>[
///           SliverOverlapAbsorber(
///             handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
///             sliver: SliverAppBar(
///               title: const Text('Snapping Nested SliverAppBar'),
///               floating: true,
///               snap: true,
///               expandedHeight: 200.0,
///               forceElevated: innerBoxIsScrolled,
///             ),
///           )
///         ];
///       },
///       body: Builder(
///         builder: (BuildContext context) {
///           return CustomScrollView(
///             // The "controller" and "primary" members should be left
///             // unset, so that the NestedScrollView can control this
///             // inner scroll view.
///             // If the "controller" property is set, then this scroll
///             // view will not be associated with the NestedScrollView.
///             slivers: <Widget>[
///               SliverOverlapInjector(handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context)),
///               SliverFixedExtentList(
///                 itemExtent: 48.0,
///                 delegate: SliverChildBuilderDelegate(
///                     (BuildContext context, int index) => ListTile(title: Text('Item $index')),
///                   childCount: 30,
///                 ),
///               ),
///             ],
///           );
///         }
///       )
///     )
///   );
/// }
/// ```
/// {@end-tool}
///
/// ### Snapping and Floating [SliverAppBar]s
///
// See https://github.com/flutter/flutter/issues/59189
/// Currently, [NestedScrollView] does not support simultaneously floating and
/// snapping the outer scrollable, e.g. when using [SliverAppBar.floating] &
/// [SliverAppBar.snap] at the same time.
///
/// ### Stretching [SliverAppBar]s
///
344
// See https://github.com/flutter/flutter/issues/54059
345 346 347 348 349 350 351 352 353 354 355
/// Currently, [NestedScrollView] does not support stretching the outer
/// scrollable, e.g. when using [SliverAppBar.stretch].
///
/// See also:
///
///  * [SliverAppBar], for examples on different configurations like floating,
///    pinned and snap behaviors.
///  * [SliverOverlapAbsorber], a sliver that wraps another, forcing its layout
///    extent to be treated as overlap.
///  * [SliverOverlapInjector], a sliver that has a sliver geometry based on
///    the values stored in a [SliverOverlapAbsorberHandle].
356
class NestedScrollView extends StatefulWidget {
357 358
  /// Creates a nested scroll view.
  ///
359 360
  /// The [reverse], [headerSliverBuilder], and [body] arguments must not be
  /// null.
361
  const NestedScrollView({
362
    Key? key,
363
    this.controller,
364 365
    this.scrollDirection = Axis.vertical,
    this.reverse = false,
366
    this.physics,
367 368
    required this.headerSliverBuilder,
    required this.body,
369
    this.dragStartBehavior = DragStartBehavior.start,
370
    this.floatHeaderSlivers = false,
371
    this.clipBehavior = Clip.hardEdge,
372
    this.restorationId,
373
    this.scrollBehavior,
374 375 376 377
  }) : assert(scrollDirection != null),
       assert(reverse != null),
       assert(headerSliverBuilder != null),
       assert(body != null),
378
       assert(floatHeaderSlivers != null),
379
       assert(clipBehavior != null),
380
       super(key: key);
381

382 383
  /// An object that can be used to control the position to which the outer
  /// scroll view is scrolled.
384
  final ScrollController? controller;
385

386 387 388
  /// The axis along which the scroll view scrolls.
  ///
  /// Defaults to [Axis.vertical].
389 390
  final Axis scrollDirection;

391 392 393 394 395 396 397 398 399 400 401 402
  /// Whether the scroll view scrolls in the reading direction.
  ///
  /// For example, if the reading direction is left-to-right and
  /// [scrollDirection] is [Axis.horizontal], then the scroll view scrolls from
  /// left to right when [reverse] is false and from right to left when
  /// [reverse] is true.
  ///
  /// Similarly, if [scrollDirection] is [Axis.vertical], then the scroll view
  /// scrolls from top to bottom when [reverse] is false and from bottom to top
  /// when [reverse] is true.
  ///
  /// Defaults to false.
403 404
  final bool reverse;

405 406 407
  /// How the scroll view should respond to user input.
  ///
  /// For example, determines how the scroll view continues to animate after the
408 409 410
  /// user stops dragging the scroll view (providing a custom implementation of
  /// [ScrollPhysics.createBallisticSimulation] allows this particular aspect of
  /// the physics to be overridden).
411
  ///
412 413 414 415
  /// If an explicit [ScrollBehavior] is provided to [scrollBehavior], the
  /// [ScrollPhysics] provided by that behavior will take precedence after
  /// [physics].
  ///
416
  /// Defaults to matching platform conventions.
417 418 419 420 421 422 423
  ///
  /// The [ScrollPhysics.applyBoundaryConditions] implementation of the provided
  /// object should not allow scrolling outside the scroll extent range
  /// described by the [ScrollMetrics.minScrollExtent] and
  /// [ScrollMetrics.maxScrollExtent] properties passed to that method. If that
  /// invariant is not maintained, the nested scroll view may respond to user
  /// scrolling erratically.
424
  final ScrollPhysics? physics;
425

426 427 428 429
  /// A builder for any widgets that are to precede the inner scroll views (as
  /// given by [body]).
  ///
  /// Typically this is used to create a [SliverAppBar] with a [TabBar].
430
  final NestedScrollViewHeaderSliversBuilder headerSliverBuilder;
431

432 433 434 435 436
  /// The widget to show inside the [NestedScrollView].
  ///
  /// Typically this will be [TabBarView].
  ///
  /// The [body] is built in a context that provides a [PrimaryScrollController]
437 438 439 440 441
  /// that interacts with the [NestedScrollView]'s scroll controller. Any
  /// [ListView] or other [Scrollable]-based widget inside the [body] that is
  /// intended to scroll with the [NestedScrollView] should therefore not be
  /// given an explicit [ScrollController], instead allowing it to default to
  /// the [PrimaryScrollController] provided by the [NestedScrollView].
442 443
  final Widget body;

444 445 446
  /// {@macro flutter.widgets.scrollable.dragStartBehavior}
  final DragStartBehavior dragStartBehavior;

447 448 449 450 451 452 453
  /// Whether or not the [NestedScrollView]'s coordinator should prioritize the
  /// outer scrollable over the inner when scrolling back.
  ///
  /// This is useful for an outer scrollable containing a [SliverAppBar] that
  /// is expected to float. This cannot be null.
  final bool floatHeaderSlivers;

454
  /// {@macro flutter.material.Material.clipBehavior}
455 456 457 458
  ///
  /// Defaults to [Clip.hardEdge].
  final Clip clipBehavior;

459
  /// {@macro flutter.widgets.scrollable.restorationId}
460
  final String? restorationId;
461

462 463 464 465 466 467 468 469 470 471 472 473 474 475
  /// {@macro flutter.widgets.shadow.scrollBehavior}
  ///
  /// [ScrollBehavior]s also provide [ScrollPhysics]. If an explicit
  /// [ScrollPhysics] is provided in [physics], it will take precedence,
  /// followed by [scrollBehavior], and then the inherited ancestor
  /// [ScrollBehavior].
  ///
  /// The [ScrollBehavior] of the inherited [ScrollConfiguration] will be
  /// modified by default to not apply a [Scrollbar]. This is because the
  /// NestedScrollView cannot assume the configuration of the outer and inner
  /// [Scrollable] widgets, particularly whether to treat them as one scrollable,
  /// or separate and desirous of unique behaviors.
  final ScrollBehavior? scrollBehavior;

476 477 478 479 480 481 482 483
  /// Returns the [SliverOverlapAbsorberHandle] of the nearest ancestor
  /// [NestedScrollView].
  ///
  /// This is necessary to configure the [SliverOverlapAbsorber] and
  /// [SliverOverlapInjector] widgets.
  ///
  /// For sample code showing how to use this method, see the [NestedScrollView]
  /// documentation.
484
  static SliverOverlapAbsorberHandle sliverOverlapAbsorberHandleFor(BuildContext context) {
485
    final _InheritedNestedScrollView? target = context.dependOnInheritedWidgetOfExactType<_InheritedNestedScrollView>();
486 487 488 489
    assert(
      target != null,
      'NestedScrollView.sliverOverlapAbsorberHandleFor must be called with a context that contains a NestedScrollView.',
    );
490
    return target!.state._absorberHandle;
491 492
  }

493
  List<Widget> _buildSlivers(BuildContext context, ScrollController innerController, bool bodyIsScrolled) {
494 495 496 497 498 499 500
    return <Widget>[
      ...headerSliverBuilder(context, bodyIsScrolled),
      SliverFillRemaining(
        child: PrimaryScrollController(
          controller: innerController,
          child: body,
        ),
501
      ),
502
    ];
503 504 505
  }

  @override
506
  NestedScrollViewState createState() => NestedScrollViewState();
507 508
}

509 510 511 512 513 514 515 516 517 518
/// The [State] for a [NestedScrollView].
///
/// The [ScrollController]s, [innerController] and [outerController], of the
/// [NestedScrollView]'s children may be accessed through its state. This is
/// useful for obtaining respective scroll positions in the [NestedScrollView].
///
/// If you want to access the inner or outer scroll controller of a
/// [NestedScrollView], you can get its [NestedScrollViewState] by supplying a
/// `GlobalKey<NestedScrollViewState>` to the [NestedScrollView.key] parameter).
///
519
/// {@tool dartpad --template=stateless_widget_material}
520 521 522 523 524 525 526 527 528 529 530 531 532
/// [NestedScrollViewState] can be obtained using a [GlobalKey].
/// Using the following setup, you can access the inner scroll controller
/// using `globalKey.currentState.innerController`.
///
/// ```dart preamble
/// final GlobalKey<NestedScrollViewState> globalKey = GlobalKey();
/// ```
/// ```dart
/// @override
/// Widget build(BuildContext context) {
///   return NestedScrollView(
///     key: globalKey,
///     headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
533
///       return const <Widget>[
534 535 536 537 538
///         SliverAppBar(
///           title: Text('NestedScrollViewState Demo!'),
///         ),
///       ];
///     },
539
///     body: const CustomScrollView(
540 541 542 543 544 545
///       // Body slivers go here!
///     ),
///   );
/// }
///
/// ScrollController get innerController {
546
///   return globalKey.currentState!.innerController;
547 548 549 550
/// }
/// ```
/// {@end-tool}
class NestedScrollViewState extends State<NestedScrollView> {
551
  final SliverOverlapAbsorberHandle _absorberHandle = SliverOverlapAbsorberHandle();
552

553 554 555 556 557 558 559 560 561 562 563
  /// The [ScrollController] provided to the [ScrollView] in
  /// [NestedScrollView.body].
  ///
  /// Manipulating the [ScrollPosition] of this controller pushes the outer
  /// header sliver(s) up and out of view. The position of the [outerController]
  /// will be set to [ScrollPosition.maxScrollExtent], unless you use
  /// [ScrollPosition.setPixels].
  ///
  /// See also:
  ///
  ///  * [outerController], which exposes the [ScrollController] used by the
Pierre-Louis's avatar
Pierre-Louis committed
564
  ///    sliver(s) contained in [NestedScrollView.headerSliverBuilder].
565
  ScrollController get innerController => _coordinator!._innerController;
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581

  /// The [ScrollController] provided to the [ScrollView] in
  /// [NestedScrollView.headerSliverBuilder].
  ///
  /// This is equivalent to [NestedScrollView.controller], if provided.
  ///
  /// Manipulating the [ScrollPosition] of this controller pushes the inner body
  /// sliver(s) down. The position of the [innerController] will be set to
  /// [ScrollPosition.minScrollExtent], unless you use
  /// [ScrollPosition.setPixels]. Visually, the inner body will be scrolled to
  /// its beginning.
  ///
  /// See also:
  ///
  ///  * [innerController], which exposes the [ScrollController] used by the
  ///    [ScrollView] contained in [NestedScrollView.body].
582
  ScrollController get outerController => _coordinator!._outerController;
583

584
  _NestedScrollCoordinator? _coordinator;
585 586 587 588

  @override
  void initState() {
    super.initState();
589
    _coordinator = _NestedScrollCoordinator(
590 591
      this,
      widget.controller,
592
      _handleHasScrolledBodyChanged,
593
      widget.floatHeaderSlivers,
594
    );
595 596 597 598 599
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
600
    _coordinator!.setParent(widget.controller);
601 602 603 604 605 606
  }

  @override
  void didUpdateWidget(NestedScrollView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.controller != widget.controller)
607
      _coordinator!.setParent(widget.controller);
608 609 610 611
  }

  @override
  void dispose() {
612
    _coordinator!.dispose();
613 614 615 616
    _coordinator = null;
    super.dispose();
  }

617
  bool? _lastHasScrolledBody;
618

619 620 621
  void _handleHasScrolledBodyChanged() {
    if (!mounted)
      return;
622
    final bool newHasScrolledBody = _coordinator!.hasScrolledBody;
623 624 625 626 627 628 629 630 631
    if (_lastHasScrolledBody != newHasScrolledBody) {
      setState(() {
        // _coordinator.hasScrolledBody changed (we use it in the build method)
        // (We record _lastHasScrolledBody in the build() method, rather than in
        // this setState call, because the build() method may be called more
        // often than just from here, and we want to only call setState when the
        // new value is different than the last built value.)
      });
    }
632 633
  }

634 635
  @override
  Widget build(BuildContext context) {
636 637 638 639
    final ScrollPhysics _scrollPhysics = widget.physics?.applyTo(const ClampingScrollPhysics())
      ?? widget.scrollBehavior?.getScrollPhysics(context).applyTo(const ClampingScrollPhysics())
      ?? const ClampingScrollPhysics();

640
    return _InheritedNestedScrollView(
641
      state: this,
642
      child: Builder(
643
        builder: (BuildContext context) {
644
          _lastHasScrolledBody = _coordinator!.hasScrolledBody;
645
          return _NestedScrollViewCustomScrollView(
646
            dragStartBehavior: widget.dragStartBehavior,
647 648
            scrollDirection: widget.scrollDirection,
            reverse: widget.reverse,
649 650
            physics: _scrollPhysics,
            scrollBehavior: widget.scrollBehavior ?? ScrollConfiguration.of(context).copyWith(scrollbars: false),
651
            controller: _coordinator!._outerController,
652 653
            slivers: widget._buildSlivers(
              context,
654 655
              _coordinator!._innerController,
              _lastHasScrolledBody!,
656 657
            ),
            handle: _absorberHandle,
658
            clipBehavior: widget.clipBehavior,
659
            restorationId: widget.restorationId,
660 661 662
          );
        },
      ),
663 664 665 666
    );
  }
}

667
class _NestedScrollViewCustomScrollView extends CustomScrollView {
668
  const _NestedScrollViewCustomScrollView({
669 670 671
    required Axis scrollDirection,
    required bool reverse,
    required ScrollPhysics physics,
672
    required ScrollBehavior scrollBehavior,
673 674 675 676
    required ScrollController controller,
    required List<Widget> slivers,
    required this.handle,
    required Clip clipBehavior,
677
    DragStartBehavior dragStartBehavior = DragStartBehavior.start,
678
    String? restorationId,
679 680 681 682
  }) : super(
         scrollDirection: scrollDirection,
         reverse: reverse,
         physics: physics,
683
         scrollBehavior: scrollBehavior,
684 685
         controller: controller,
         slivers: slivers,
686
         dragStartBehavior: dragStartBehavior,
687
         restorationId: restorationId,
688
         clipBehavior: clipBehavior,
689 690 691 692 693 694 695 696 697 698 699 700
       );

  final SliverOverlapAbsorberHandle handle;

  @override
  Widget buildViewport(
    BuildContext context,
    ViewportOffset offset,
    AxisDirection axisDirection,
    List<Widget> slivers,
  ) {
    assert(!shrinkWrap);
701
    return NestedScrollViewViewport(
702 703 704 705
      axisDirection: axisDirection,
      offset: offset,
      slivers: slivers,
      handle: handle,
706
      clipBehavior: clipBehavior,
707 708 709 710 711 712
    );
  }
}

class _InheritedNestedScrollView extends InheritedWidget {
  const _InheritedNestedScrollView({
713 714 715
    Key? key,
    required this.state,
    required Widget child,
716 717 718 719
  }) : assert(state != null),
       assert(child != null),
       super(key: key, child: child);

720
  final NestedScrollViewState state;
721 722 723 724 725

  @override
  bool updateShouldNotify(_InheritedNestedScrollView old) => state != old.state;
}

726 727
class _NestedScrollMetrics extends FixedScrollMetrics {
  _NestedScrollMetrics({
728 729 730 731
    required double? minScrollExtent,
    required double? maxScrollExtent,
    required double? pixels,
    required double? viewportDimension,
732 733 734 735
    required AxisDirection axisDirection,
    required this.minRange,
    required this.maxRange,
    required this.correctionOffset,
736 737 738 739 740 741 742 743
  }) : super(
    minScrollExtent: minScrollExtent,
    maxScrollExtent: maxScrollExtent,
    pixels: pixels,
    viewportDimension: viewportDimension,
    axisDirection: axisDirection,
  );

744 745
  @override
  _NestedScrollMetrics copyWith({
746 747 748 749 750 751 752 753
    double? minScrollExtent,
    double? maxScrollExtent,
    double? pixels,
    double? viewportDimension,
    AxisDirection? axisDirection,
    double? minRange,
    double? maxRange,
    double? correctionOffset,
754
  }) {
755
    return _NestedScrollMetrics(
756 757 758 759
      minScrollExtent: minScrollExtent ?? (hasContentDimensions ? this.minScrollExtent : null),
      maxScrollExtent: maxScrollExtent ?? (hasContentDimensions ? this.maxScrollExtent : null),
      pixels: pixels ?? (hasPixels ? this.pixels : null),
      viewportDimension: viewportDimension ?? (hasViewportDimension ? this.viewportDimension : null),
760 761 762 763 764 765 766
      axisDirection: axisDirection ?? this.axisDirection,
      minRange: minRange ?? this.minRange,
      maxRange: maxRange ?? this.maxRange,
      correctionOffset: correctionOffset ?? this.correctionOffset,
    );
  }

767 768 769 770 771 772 773
  final double minRange;

  final double maxRange;

  final double correctionOffset;
}

774
typedef _NestedScrollActivityGetter = ScrollActivity Function(_NestedScrollPosition position);
775

776
class _NestedScrollCoordinator implements ScrollActivityDelegate, ScrollHoldController {
777 778 779 780 781 782
  _NestedScrollCoordinator(
    this._state,
    this._parent,
    this._onHasScrolledBodyChanged,
    this._floatHeaderSlivers,
  ) {
783
    final double initialScrollOffset = _parent?.initialScrollOffset ?? 0.0;
784 785 786 787 788 789 790 791 792 793
    _outerController = _NestedScrollController(
      this,
      initialScrollOffset: initialScrollOffset,
      debugLabel: 'outer',
    );
    _innerController = _NestedScrollController(
      this,
      initialScrollOffset: 0.0,
      debugLabel: 'inner',
    );
794 795
  }

796
  final NestedScrollViewState _state;
797
  ScrollController? _parent;
798
  final VoidCallback _onHasScrolledBodyChanged;
799
  final bool _floatHeaderSlivers;
800

801 802
  late _NestedScrollController _outerController;
  late _NestedScrollController _innerController;
803

804
  _NestedScrollPosition? get _outerPosition {
805 806 807 808 809 810 811 812 813
    if (!_outerController.hasClients)
      return null;
    return _outerController.nestedPositions.single;
  }

  Iterable<_NestedScrollPosition> get _innerPositions {
    return _innerController.nestedPositions;
  }

814
  bool get canScrollBody {
815
    final _NestedScrollPosition? outer = _outerPosition;
816 817 818 819 820
    if (outer == null)
      return true;
    return outer.haveDimensions && outer.extentAfter == 0.0;
  }

821
  bool get hasScrolledBody {
822
    for (final _NestedScrollPosition position in _innerPositions) {
823 824 825 826 827 828 829
      if (!position.hasContentDimensions || !position.hasPixels) {
        // It's possible that NestedScrollView built twice before layout phase
        // in the same frame. This can happen when the FocusManager schedules a microTask
        // that marks NestedScrollView dirty during the warm up frame.
        // https://github.com/flutter/flutter/pull/75308
        continue;
      } else if (position.pixels > position.minScrollExtent) {
830
        return true;
831
      }
832 833 834 835
    }
    return false;
  }

836
  void updateShadow() { _onHasScrolledBodyChanged(); }
837

838 839 840 841 842 843 844 845
  ScrollDirection get userScrollDirection => _userScrollDirection;
  ScrollDirection _userScrollDirection = ScrollDirection.idle;

  void updateUserScrollDirection(ScrollDirection value) {
    assert(value != null);
    if (userScrollDirection == value)
      return;
    _userScrollDirection = value;
846
    _outerPosition!.didUpdateScrollDirection(value);
847
    for (final _NestedScrollPosition position in _innerPositions)
848 849 850
      position.didUpdateScrollDirection(value);
  }

851
  ScrollDragController? _currentDrag;
852 853

  void beginActivity(ScrollActivity newOuterActivity, _NestedScrollActivityGetter innerActivityGetter) {
854
    _outerPosition!.beginActivity(newOuterActivity);
855
    bool scrolling = newOuterActivity.isScrolling;
856
    for (final _NestedScrollPosition position in _innerPositions) {
857 858 859 860 861 862 863 864 865 866 867
      final ScrollActivity newInnerActivity = innerActivityGetter(position);
      position.beginActivity(newInnerActivity);
      scrolling = scrolling && newInnerActivity.isScrolling;
    }
    _currentDrag?.dispose();
    _currentDrag = null;
    if (!scrolling)
      updateUserScrollDirection(ScrollDirection.idle);
  }

  @override
868
  AxisDirection get axisDirection => _outerPosition!.axisDirection;
869 870

  static IdleScrollActivity _createIdleScrollActivity(_NestedScrollPosition position) {
871
    return IdleScrollActivity(position);
872 873 874 875
  }

  @override
  void goIdle() {
876
    beginActivity(
877
      _createIdleScrollActivity(_outerPosition!),
878 879
      _createIdleScrollActivity,
    );
880 881 882 883 884 885
  }

  @override
  void goBallistic(double velocity) {
    beginActivity(
      createOuterBallisticScrollActivity(velocity),
886 887 888 889 890 891
      (_NestedScrollPosition position) {
        return createInnerBallisticScrollActivity(
          position,
          velocity,
        );
      },
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
    );
  }

  ScrollActivity createOuterBallisticScrollActivity(double velocity) {
    // This function creates a ballistic scroll for the outer scrollable.
    //
    // It assumes that the outer scrollable can't be overscrolled, and sets up a
    // ballistic scroll over the combined space of the innerPositions and the
    // outerPosition.

    // First we must pick a representative inner position that we will care
    // about. This is somewhat arbitrary. Ideally we'd pick the one that is "in
    // the center" but there isn't currently a good way to do that so we
    // arbitrarily pick the one that is the furthest away from the infinity we
    // are heading towards.
907
    _NestedScrollPosition? innerPosition;
908
    if (velocity != 0.0) {
909
      for (final _NestedScrollPosition position in _innerPositions) {
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
        if (innerPosition != null) {
          if (velocity > 0.0) {
            if (innerPosition.pixels < position.pixels)
              continue;
          } else {
            assert(velocity < 0.0);
            if (innerPosition.pixels > position.pixels)
              continue;
          }
        }
        innerPosition = position;
      }
    }

    if (innerPosition == null) {
      // It's either just us or a velocity=0 situation.
926 927 928
      return _outerPosition!.createBallisticScrollActivity(
        _outerPosition!.physics.createBallisticSimulation(
          _outerPosition!,
929 930
          velocity,
        ),
931 932 933 934 935 936
        mode: _NestedBallisticScrollActivityMode.independent,
      );
    }

    final _NestedScrollMetrics metrics = _getMetrics(innerPosition, velocity);

937 938
    return _outerPosition!.createBallisticScrollActivity(
      _outerPosition!.physics.createBallisticSimulation(metrics, velocity),
939 940 941 942 943 944 945 946 947
      mode: _NestedBallisticScrollActivityMode.outer,
      metrics: metrics,
    );
  }

  @protected
  ScrollActivity createInnerBallisticScrollActivity(_NestedScrollPosition position, double velocity) {
    return position.createBallisticScrollActivity(
      position.physics.createBallisticSimulation(
948
        _getMetrics(position, velocity),
949 950 951 952 953 954 955 956
        velocity,
      ),
      mode: _NestedBallisticScrollActivityMode.inner,
    );
  }

  _NestedScrollMetrics _getMetrics(_NestedScrollPosition innerPosition, double velocity) {
    assert(innerPosition != null);
957 958
    double pixels, minRange, maxRange, correctionOffset;
    double extra = 0.0;
959
    if (innerPosition.pixels == innerPosition.minScrollExtent) {
960 961 962 963 964 965
      pixels = _outerPosition!.pixels.clamp(
        _outerPosition!.minScrollExtent,
        _outerPosition!.maxScrollExtent,
      ); // TODO(ianh): gracefully handle out-of-range outer positions
      minRange = _outerPosition!.minScrollExtent;
      maxRange = _outerPosition!.maxScrollExtent;
966 967 968 969 970
      assert(minRange <= maxRange);
      correctionOffset = 0.0;
    } else {
      assert(innerPosition.pixels != innerPosition.minScrollExtent);
      if (innerPosition.pixels < innerPosition.minScrollExtent) {
971
        pixels = innerPosition.pixels - innerPosition.minScrollExtent + _outerPosition!.minScrollExtent;
972 973
      } else {
        assert(innerPosition.pixels > innerPosition.minScrollExtent);
974
        pixels = innerPosition.pixels - innerPosition.minScrollExtent + _outerPosition!.maxScrollExtent;
975 976 977 978
      }
      if ((velocity > 0.0) && (innerPosition.pixels > innerPosition.minScrollExtent)) {
        // This handles going forward (fling up) and inner list is scrolled past
        // zero. We want to grab the extra pixels immediately to shrink.
979
        extra = _outerPosition!.maxScrollExtent - _outerPosition!.pixels;
980 981 982 983
        assert(extra >= 0.0);
        minRange = pixels;
        maxRange = pixels + extra;
        assert(minRange <= maxRange);
984
        correctionOffset = _outerPosition!.pixels - pixels;
985 986 987
      } else if ((velocity < 0.0) && (innerPosition.pixels < innerPosition.minScrollExtent)) {
        // This handles going backward (fling down) and inner list is
        // underscrolled. We want to grab the extra pixels immediately to grow.
988
        extra = _outerPosition!.pixels - _outerPosition!.minScrollExtent;
989 990 991 992
        assert(extra >= 0.0);
        minRange = pixels - extra;
        maxRange = pixels;
        assert(minRange <= maxRange);
993
        correctionOffset = _outerPosition!.pixels - pixels;
994 995 996 997 998 999 1000
      } else {
        // This handles going forward (fling up) and inner list is
        // underscrolled, OR, going backward (fling down) and inner list is
        // scrolled past zero. We want to skip the pixels we don't need to grow
        // or shrink over.
        if (velocity > 0.0) {
          // shrinking
1001
          extra = _outerPosition!.minScrollExtent - _outerPosition!.pixels;
1002
        } else if (velocity < 0.0) {
1003
          // growing
1004
          extra = _outerPosition!.pixels - (_outerPosition!.maxScrollExtent - _outerPosition!.minScrollExtent);
1005 1006
        }
        assert(extra <= 0.0);
1007 1008
        minRange = _outerPosition!.minScrollExtent;
        maxRange = _outerPosition!.maxScrollExtent + extra;
1009 1010 1011 1012
        assert(minRange <= maxRange);
        correctionOffset = 0.0;
      }
    }
1013
    return _NestedScrollMetrics(
1014 1015
      minScrollExtent: _outerPosition!.minScrollExtent,
      maxScrollExtent: _outerPosition!.maxScrollExtent + innerPosition.maxScrollExtent - innerPosition.minScrollExtent + extra,
1016
      pixels: pixels,
1017 1018
      viewportDimension: _outerPosition!.viewportDimension,
      axisDirection: _outerPosition!.axisDirection,
1019 1020 1021 1022 1023 1024 1025 1026
      minRange: minRange,
      maxRange: maxRange,
      correctionOffset: correctionOffset,
    );
  }

  double unnestOffset(double value, _NestedScrollPosition source) {
    if (source == _outerPosition)
1027
      return value.clamp(
1028 1029 1030
        _outerPosition!.minScrollExtent,
        _outerPosition!.maxScrollExtent,
      );
1031
    if (value < source.minScrollExtent)
1032 1033
      return value - source.minScrollExtent + _outerPosition!.minScrollExtent;
    return value - source.minScrollExtent + _outerPosition!.maxScrollExtent;
1034 1035 1036 1037
  }

  double nestOffset(double value, _NestedScrollPosition target) {
    if (target == _outerPosition)
1038
      return value.clamp(
1039 1040 1041 1042 1043 1044 1045
        _outerPosition!.minScrollExtent,
        _outerPosition!.maxScrollExtent,
      );
    if (value < _outerPosition!.minScrollExtent)
      return value - _outerPosition!.minScrollExtent + target.minScrollExtent;
    if (value > _outerPosition!.maxScrollExtent)
      return value - _outerPosition!.maxScrollExtent + target.minScrollExtent;
1046 1047 1048 1049
    return target.minScrollExtent;
  }

  void updateCanDrag() {
1050
    if (!_outerPosition!.haveDimensions)
1051 1052
      return;
    double maxInnerExtent = 0.0;
1053
    for (final _NestedScrollPosition position in _innerPositions) {
1054 1055
      if (!position.haveDimensions)
        return;
1056 1057 1058 1059
      maxInnerExtent = math.max(
        maxInnerExtent,
        position.maxScrollExtent - position.minScrollExtent,
      );
1060
    }
1061
    _outerPosition!.updateCanDrag(maxInnerExtent);
1062 1063
  }

1064 1065
  Future<void> animateTo(
    double to, {
1066 1067
    required Duration duration,
    required Curve curve,
1068
  }) async {
1069 1070
    final DrivenScrollActivity outerActivity = _outerPosition!.createDrivenScrollActivity(
      nestOffset(to, _outerPosition!),
1071 1072 1073
      duration,
      curve,
    );
1074
    final List<Future<void>> resultFutures = <Future<void>>[outerActivity.done];
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    beginActivity(
      outerActivity,
      (_NestedScrollPosition position) {
        final DrivenScrollActivity innerActivity = position.createDrivenScrollActivity(
          nestOffset(to, position),
          duration,
          curve,
        );
        resultFutures.add(innerActivity.done);
        return innerActivity;
      },
    );
1087
    await Future.wait<void>(resultFutures);
1088 1089 1090 1091
  }

  void jumpTo(double to) {
    goIdle();
1092
    _outerPosition!.localJumpTo(nestOffset(to, _outerPosition!));
1093
    for (final _NestedScrollPosition position in _innerPositions)
1094 1095 1096 1097
      position.localJumpTo(nestOffset(to, position));
    goBallistic(0.0);
  }

1098 1099 1100 1101 1102
  void pointerScroll(double delta) {
    assert(delta != 0.0);

    goIdle();
    updateUserScrollDirection(
1103
        delta < 0.0 ? ScrollDirection.forward : ScrollDirection.reverse,
1104 1105
    );

1106 1107 1108 1109 1110 1111 1112
    // Set the isScrollingNotifier. Even if only one position actually receives
    // the delta, the NestedScrollView's intention is to treat multiple
    // ScrollPositions as one.
    _outerPosition!.isScrollingNotifier.value = true;
    for (final _NestedScrollPosition position in _innerPositions)
      position.isScrollingNotifier.value = true;

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
    if (_innerPositions.isEmpty) {
      // Does not enter overscroll.
      _outerPosition!.applyClampedPointerSignalUpdate(delta);
    } else if (delta > 0.0) {
      // Dragging "up" - delta is positive
      // Prioritize getting rid of any inner overscroll, and then the outer
      // view, so that the app bar will scroll out of the way asap.
      double outerDelta = delta;
      for (final _NestedScrollPosition position in _innerPositions) {
        if (position.pixels < 0.0) { // This inner position is in overscroll.
          final double potentialOuterDelta = position.applyClampedPointerSignalUpdate(delta);
          // In case there are multiple positions in varying states of
          // overscroll, the first to 'reach' the outer view above takes
          // precedence.
          outerDelta = math.max(outerDelta, potentialOuterDelta);
        }
      }
      if (outerDelta != 0.0) {
        final double innerDelta = _outerPosition!.applyClampedPointerSignalUpdate(
1132
            outerDelta,
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
        );
        if (innerDelta != 0.0) {
          for (final _NestedScrollPosition position in _innerPositions)
            position.applyClampedPointerSignalUpdate(innerDelta);
        }
      }
    } else {
      // Dragging "down" - delta is negative
      double innerDelta = delta;
      // Apply delta to the outer header first if it is configured to float.
      if (_floatHeaderSlivers)
        innerDelta = _outerPosition!.applyClampedPointerSignalUpdate(delta);

      if (innerDelta != 0.0) {
        // Apply the innerDelta, if we have not floated in the outer scrollable,
        // any leftover delta after this will be passed on to the outer
        // scrollable by the outerDelta.
        double outerDelta = 0.0; // it will go negative if it changes
        for (final _NestedScrollPosition position in _innerPositions) {
          final double overscroll = position.applyClampedPointerSignalUpdate(innerDelta);
          outerDelta = math.min(outerDelta, overscroll);
        }
        if (outerDelta != 0.0)
          _outerPosition!.applyClampedPointerSignalUpdate(outerDelta);
      }
    }
    goBallistic(0.0);
  }

1162 1163 1164 1165 1166 1167
  @override
  double setPixels(double newPixels) {
    assert(false);
    return 0.0;
  }

1168 1169
  ScrollHoldController hold(VoidCallback holdCancelCallback) {
    beginActivity(
1170
      HoldScrollActivity(
1171
        delegate: _outerPosition!,
1172 1173
        onHoldCanceled: holdCancelCallback,
      ),
1174
      (_NestedScrollPosition position) => HoldScrollActivity(delegate: position),
1175 1176 1177 1178 1179 1180 1181
    );
    return this;
  }

  @override
  void cancel() {
    goBallistic(0.0);
1182 1183 1184
  }

  Drag drag(DragStartDetails details, VoidCallback dragCancelCallback) {
1185
    final ScrollDragController drag = ScrollDragController(
1186 1187 1188
      delegate: this,
      details: details,
      onDragCanceled: dragCancelCallback,
1189 1190
    );
    beginActivity(
1191
      DragScrollActivity(_outerPosition!, drag),
1192
      (_NestedScrollPosition position) => DragScrollActivity(position, drag),
1193 1194 1195 1196 1197 1198 1199 1200
    );
    assert(_currentDrag == null);
    _currentDrag = drag;
    return drag;
  }

  @override
  void applyUserOffset(double delta) {
1201
    updateUserScrollDirection(
1202
      delta > 0.0 ? ScrollDirection.forward : ScrollDirection.reverse,
1203
    );
1204 1205
    assert(delta != 0.0);
    if (_innerPositions.isEmpty) {
1206
      _outerPosition!.applyFullDragUpdate(delta);
1207
    } else if (delta < 0.0) {
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
      // Dragging "up"
      // Prioritize getting rid of any inner overscroll, and then the outer
      // view, so that the app bar will scroll out of the way asap.
      double outerDelta = delta;
      for (final _NestedScrollPosition position in _innerPositions) {
        if (position.pixels < 0.0) { // This inner position is in overscroll.
          final double potentialOuterDelta = position.applyClampedDragUpdate(delta);
          // In case there are multiple positions in varying states of
          // overscroll, the first to 'reach' the outer view above takes
          // precedence.
          outerDelta = math.max(outerDelta, potentialOuterDelta);
        }
      }
      if (outerDelta != 0.0) {
1222
        final double innerDelta = _outerPosition!.applyClampedDragUpdate(
1223
          outerDelta,
1224 1225 1226 1227 1228
        );
        if (innerDelta != 0.0) {
          for (final _NestedScrollPosition position in _innerPositions)
            position.applyFullDragUpdate(innerDelta);
        }
1229 1230
      }
    } else {
1231
      // Dragging "down" - delta is positive
1232 1233 1234
      double innerDelta = delta;
      // Apply delta to the outer header first if it is configured to float.
      if (_floatHeaderSlivers)
1235
        innerDelta = _outerPosition!.applyClampedDragUpdate(delta);
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249

      if (innerDelta != 0.0) {
        // Apply the innerDelta, if we have not floated in the outer scrollable,
        // any leftover delta after this will be passed on to the outer
        // scrollable by the outerDelta.
        double outerDelta = 0.0; // it will go positive if it changes
        final List<double> overscrolls = <double>[];
        final List<_NestedScrollPosition> innerPositions = _innerPositions.toList();
        for (final _NestedScrollPosition position in innerPositions) {
          final double overscroll = position.applyClampedDragUpdate(innerDelta);
          outerDelta = math.max(outerDelta, overscroll);
          overscrolls.add(overscroll);
        }
        if (outerDelta != 0.0)
1250
          outerDelta -= _outerPosition!.applyClampedDragUpdate(outerDelta);
1251 1252 1253 1254 1255 1256 1257

        // Now deal with any overscroll
        for (int i = 0; i < innerPositions.length; ++i) {
          final double remainingDelta = overscrolls[i] - outerDelta;
          if (remainingDelta > 0.0)
            innerPositions[i].applyFullDragUpdate(remainingDelta);
        }
1258 1259 1260 1261
      }
    }
  }

1262
  void setParent(ScrollController? value) {
1263 1264 1265 1266
    _parent = value;
    updateParent();
  }

1267
  void updateParent() {
1268
    _outerPosition?.setParent(
1269
      _parent ?? PrimaryScrollController.of(_state.context),
1270
    );
1271 1272 1273 1274 1275 1276 1277 1278 1279
  }

  @mustCallSuper
  void dispose() {
    _currentDrag?.dispose();
    _currentDrag = null;
    _outerController.dispose();
    _innerController.dispose();
  }
1280 1281

  @override
1282
  String toString() => '${objectRuntimeType(this, '_NestedScrollCoordinator')}(outer=$_outerController; inner=$_innerController)';
1283 1284 1285
}

class _NestedScrollController extends ScrollController {
1286 1287
  _NestedScrollController(
    this.coordinator, {
1288
    double initialScrollOffset = 0.0,
1289
    String? debugLabel,
1290 1291
  }) : super(initialScrollOffset: initialScrollOffset, debugLabel: debugLabel);

1292
  final _NestedScrollCoordinator coordinator;
1293 1294 1295 1296 1297

  @override
  ScrollPosition createScrollPosition(
    ScrollPhysics physics,
    ScrollContext context,
1298
    ScrollPosition? oldPosition,
1299
  ) {
1300
    return _NestedScrollPosition(
1301
      coordinator: coordinator,
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
      physics: physics,
      context: context,
      initialPixels: initialScrollOffset,
      oldPosition: oldPosition,
      debugLabel: debugLabel,
    );
  }

  @override
  void attach(ScrollPosition position) {
    assert(position is _NestedScrollPosition);
    super.attach(position);
1314 1315
    coordinator.updateParent();
    coordinator.updateCanDrag();
1316
    position.addListener(_scheduleUpdateShadow);
1317 1318 1319 1320 1321 1322
    _scheduleUpdateShadow();
  }

  @override
  void detach(ScrollPosition position) {
    assert(position is _NestedScrollPosition);
1323
    (position as _NestedScrollPosition).setParent(null);
1324
    position.removeListener(_scheduleUpdateShadow);
1325 1326 1327 1328 1329 1330
    super.detach(position);
    _scheduleUpdateShadow();
  }

  void _scheduleUpdateShadow() {
    // We do this asynchronously for attach() so that the new position has had
1331 1332 1333 1334
    // time to be initialized, and we do it asynchronously for detach() and from
    // the position change notifications because those happen synchronously
    // during a frame, at a time where it's too late to call setState. Since the
    // result is usually animated, the lag incurred is no big deal.
1335
    SchedulerBinding.instance!.addPostFrameCallback(
1336 1337
      (Duration timeStamp) {
        coordinator.updateShadow();
1338
      },
1339
    );
1340 1341 1342
  }

  Iterable<_NestedScrollPosition> get nestedPositions sync* {
1343
    // TODO(vegorov): use instance method version of castFrom when it is available.
1344
    yield* Iterable.castFrom<ScrollPosition, _NestedScrollPosition>(positions);
1345 1346 1347
  }
}

1348 1349 1350 1351
// The _NestedScrollPosition is used by both the inner and outer viewports of a
// NestedScrollView. It tracks the offset to use for those viewports, and knows
// about the _NestedScrollCoordinator, so that when activities are triggered on
// this class, they can defer, or be influenced by, the coordinator.
1352 1353
class _NestedScrollPosition extends ScrollPosition implements ScrollActivityDelegate {
  _NestedScrollPosition({
1354 1355
    required ScrollPhysics physics,
    required ScrollContext context,
1356
    double initialPixels = 0.0,
1357 1358 1359
    ScrollPosition? oldPosition,
    String? debugLabel,
    required this.coordinator,
1360 1361 1362 1363 1364 1365
  }) : super(
    physics: physics,
    context: context,
    oldPosition: oldPosition,
    debugLabel: debugLabel,
  ) {
1366
    if (!hasPixels && initialPixels != null)
1367 1368 1369 1370
      correctPixels(initialPixels);
    if (activity == null)
      goIdle();
    assert(activity != null);
1371
    saveScrollOffset(); // in case we didn't restore but could, so that we don't restore it later
1372 1373
  }

1374
  final _NestedScrollCoordinator coordinator;
1375 1376 1377

  TickerProvider get vsync => context.vsync;

1378
  ScrollController? _parent;
1379

1380
  void setParent(ScrollController? value) {
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
    _parent?.detach(this);
    _parent = value;
    _parent?.attach(this);
  }

  @override
  AxisDirection get axisDirection => context.axisDirection;

  @override
  void absorb(ScrollPosition other) {
    super.absorb(other);
1392
    activity!.updateDelegate(this);
1393 1394
  }

1395 1396 1397 1398 1399 1400
  @override
  void restoreScrollOffset() {
    if (coordinator.canScrollBody)
      super.restoreScrollOffset();
  }

1401
  // Returns the amount of delta that was not used.
1402 1403 1404
  //
  // Positive delta means going down (exposing stuff above), negative delta
  // going up (exposing stuff below).
1405 1406
  double applyClampedDragUpdate(double delta) {
    assert(delta != 0.0);
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
    // If we are going towards the maxScrollExtent (negative scroll offset),
    // then the furthest we can be in the minScrollExtent direction is negative
    // infinity. For example, if we are already overscrolled, then scrolling to
    // reduce the overscroll should not disallow the overscroll.
    //
    // If we are going towards the minScrollExtent (positive scroll offset),
    // then the furthest we can be in the minScrollExtent direction is wherever
    // we are now, if we are already overscrolled (in which case pixels is less
    // than the minScrollExtent), or the minScrollExtent if we are not.
    //
    // In other words, we cannot, via applyClampedDragUpdate, _enter_ an
    // overscroll situation.
    //
    // An overscroll situation might be nonetheless entered via several means.
    // One is if the physics allow it, via applyFullDragUpdate (see below). An
    // overscroll situation can also be forced, e.g. if the scroll position is
    // artificially set using the scroll controller.
1424 1425 1426
    final double min = delta < 0.0
      ? -double.infinity
      : math.min(minScrollExtent, pixels);
1427
    // The logic for max is equivalent but on the other side.
1428 1429
    final double max = delta > 0.0
      ? double.infinity
1430 1431 1432
      // If pixels < 0.0, then we are currently in overscroll. The max should be
      // 0.0, representing the end of the overscrolled portion.
      : pixels < 0.0 ? 0.0 : math.max(maxScrollExtent, pixels);
1433
    final double oldPixels = pixels;
1434
    final double newPixels = (pixels - delta).clamp(min, max);
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
    final double clampedDelta = newPixels - pixels;
    if (clampedDelta == 0.0)
      return delta;
    final double overscroll = physics.applyBoundaryConditions(this, newPixels);
    final double actualNewPixels = newPixels - overscroll;
    final double offset = actualNewPixels - oldPixels;
    if (offset != 0.0) {
      forcePixels(actualNewPixels);
      didUpdateScrollPositionBy(offset);
    }
    return delta + offset;
  }

  // Returns the overscroll.
  double applyFullDragUpdate(double delta) {
    assert(delta != 0.0);
    final double oldPixels = pixels;
1452
    // Apply friction:
1453 1454 1455 1456
    final double newPixels = pixels - physics.applyPhysicsToUserOffset(
      this,
      delta,
    );
1457 1458
    if (oldPixels == newPixels)
      return 0.0; // delta must have been so small we dropped it during floating point addition
1459
    // Check for overscroll:
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
    final double overscroll = physics.applyBoundaryConditions(this, newPixels);
    final double actualNewPixels = newPixels - overscroll;
    if (actualNewPixels != oldPixels) {
      forcePixels(actualNewPixels);
      didUpdateScrollPositionBy(actualNewPixels - oldPixels);
    }
    if (overscroll != 0.0) {
      didOverscrollBy(overscroll);
      return overscroll;
    }
    return 0.0;
  }

1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498

  // Returns the amount of delta that was not used.
  //
  // Negative delta represents a forward ScrollDirection, while the positive
  // would be a reverse ScrollDirection.
  //
  // The method doesn't take into account the effects of [ScrollPhysics].
  double applyClampedPointerSignalUpdate(double delta) {
    assert(delta != 0.0);

    final double min = delta > 0.0
        ? -double.infinity
        : math.min(minScrollExtent, pixels);
    // The logic for max is equivalent but on the other side.
    final double max = delta < 0.0
        ? double.infinity
        : math.max(maxScrollExtent, pixels);
    final double newPixels = (pixels + delta).clamp(min, max);
    final double clampedDelta = newPixels - pixels;
    if (clampedDelta == 0.0)
      return delta;
    forcePixels(newPixels);
    didUpdateScrollPositionBy(clampedDelta);
    return delta - clampedDelta;
  }

1499
  @override
1500
  ScrollDirection get userScrollDirection => coordinator.userScrollDirection;
1501 1502

  DrivenScrollActivity createDrivenScrollActivity(double to, Duration duration, Curve curve) {
1503
    return DrivenScrollActivity(
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
      this,
      from: pixels,
      to: to,
      duration: duration,
      curve: curve,
      vsync: vsync,
    );
  }

  @override
  double applyUserOffset(double delta) {
    assert(false);
    return 0.0;
  }

  // This is called by activities when they finish their work.
  @override
  void goIdle() {
1522
    beginActivity(IdleScrollActivity(this));
1523 1524
  }

1525 1526
  // This is called by activities when they finish their work and want to go
  // ballistic.
1527 1528
  @override
  void goBallistic(double velocity) {
1529
    Simulation? simulation;
1530 1531 1532 1533 1534 1535 1536 1537
    if (velocity != 0.0 || outOfRange)
      simulation = physics.createBallisticSimulation(this, velocity);
    beginActivity(createBallisticScrollActivity(
      simulation,
      mode: _NestedBallisticScrollActivityMode.independent,
    ));
  }

1538
  ScrollActivity createBallisticScrollActivity(
1539 1540 1541
    Simulation? simulation, {
    required _NestedBallisticScrollActivityMode mode,
    _NestedScrollMetrics? metrics,
1542 1543
  }) {
    if (simulation == null)
1544
      return IdleScrollActivity(this);
1545 1546 1547 1548
    assert(mode != null);
    switch (mode) {
      case _NestedBallisticScrollActivityMode.outer:
        assert(metrics != null);
1549
        if (metrics!.minRange == metrics.maxRange)
1550
          return IdleScrollActivity(this);
1551 1552 1553 1554 1555 1556 1557
        return _NestedOuterBallisticScrollActivity(
          coordinator,
          this,
          metrics,
          simulation,
          context.vsync,
        );
1558
      case _NestedBallisticScrollActivityMode.inner:
1559 1560 1561 1562 1563 1564
        return _NestedInnerBallisticScrollActivity(
          coordinator,
          this,
          simulation,
          context.vsync,
        );
1565
      case _NestedBallisticScrollActivityMode.independent:
1566
        return BallisticScrollActivity(this, simulation, context.vsync);
1567 1568 1569 1570
    }
  }

  @override
1571 1572
  Future<void> animateTo(
    double to, {
1573 1574
    required Duration duration,
    required Curve curve,
1575
  }) {
1576 1577 1578 1579 1580
    return coordinator.animateTo(
      coordinator.unnestOffset(to, this),
      duration: duration,
      curve: curve,
    );
1581 1582 1583 1584
  }

  @override
  void jumpTo(double value) {
1585
    return coordinator.jumpTo(coordinator.unnestOffset(value, this));
1586 1587
  }

1588 1589 1590 1591 1592 1593
  @override
  void pointerScroll(double delta) {
    return coordinator.pointerScroll(delta);
  }


1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
  @override
  void jumpToWithoutSettling(double value) {
    assert(false);
  }

  void localJumpTo(double value) {
    if (pixels != value) {
      final double oldPixels = pixels;
      forcePixels(value);
      didStartScroll();
      didUpdateScrollPositionBy(pixels - oldPixels);
      didEndScroll();
    }
  }

  @override
  void applyNewDimensions() {
    super.applyNewDimensions();
1612
    coordinator.updateCanDrag();
1613 1614 1615 1616 1617 1618 1619
  }

  void updateCanDrag(double totalExtent) {
    context.setCanDrag(totalExtent > (viewportDimension - maxScrollExtent) || minScrollExtent != maxScrollExtent);
  }

  @override
1620 1621
  ScrollHoldController hold(VoidCallback holdCancelCallback) {
    return coordinator.hold(holdCancelCallback);
1622 1623 1624 1625
  }

  @override
  Drag drag(DragStartDetails details, VoidCallback dragCancelCallback) {
1626
    return coordinator.drag(details, dragCancelCallback);
1627 1628 1629 1630 1631 1632 1633
  }
}

enum _NestedBallisticScrollActivityMode { outer, inner, independent }

class _NestedInnerBallisticScrollActivity extends BallisticScrollActivity {
  _NestedInnerBallisticScrollActivity(
1634
    this.coordinator,
1635 1636 1637 1638 1639
    _NestedScrollPosition position,
    Simulation simulation,
    TickerProvider vsync,
  ) : super(position, simulation, vsync);

1640
  final _NestedScrollCoordinator coordinator;
1641 1642

  @override
1643
  _NestedScrollPosition get delegate => super.delegate as _NestedScrollPosition;
1644 1645 1646

  @override
  void resetActivity() {
1647 1648 1649 1650
    delegate.beginActivity(coordinator.createInnerBallisticScrollActivity(
      delegate,
      velocity,
    ));
1651 1652 1653 1654
  }

  @override
  void applyNewDimensions() {
1655 1656 1657 1658
    delegate.beginActivity(coordinator.createInnerBallisticScrollActivity(
      delegate,
      velocity,
    ));
1659 1660 1661 1662
  }

  @override
  bool applyMoveTo(double value) {
1663
    return super.applyMoveTo(coordinator.nestOffset(value, delegate));
1664 1665 1666 1667 1668
  }
}

class _NestedOuterBallisticScrollActivity extends BallisticScrollActivity {
  _NestedOuterBallisticScrollActivity(
1669
    this.coordinator,
1670 1671 1672 1673
    _NestedScrollPosition position,
    this.metrics,
    Simulation simulation,
    TickerProvider vsync,
1674 1675 1676
  ) : assert(metrics.minRange != metrics.maxRange),
      assert(metrics.maxRange > metrics.minRange),
      super(position, simulation, vsync);
1677

1678
  final _NestedScrollCoordinator coordinator;
1679 1680 1681
  final _NestedScrollMetrics metrics;

  @override
1682
  _NestedScrollPosition get delegate => super.delegate as _NestedScrollPosition;
1683 1684 1685

  @override
  void resetActivity() {
1686
    delegate.beginActivity(
1687
      coordinator.createOuterBallisticScrollActivity(velocity),
1688
    );
1689 1690 1691 1692
  }

  @override
  void applyNewDimensions() {
1693
    delegate.beginActivity(
1694
      coordinator.createOuterBallisticScrollActivity(velocity),
1695
    );
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
  }

  @override
  bool applyMoveTo(double value) {
    bool done = false;
    if (velocity > 0.0) {
      if (value < metrics.minRange)
        return true;
      if (value > metrics.maxRange) {
        value = metrics.maxRange;
        done = true;
      }
    } else if (velocity < 0.0) {
      if (value > metrics.maxRange)
        return true;
      if (value < metrics.minRange) {
        value = metrics.minRange;
        done = true;
      }
    } else {
1716
      value = value.clamp(metrics.minRange, metrics.maxRange);
1717 1718 1719 1720 1721 1722 1723 1724 1725
      done = true;
    }
    final bool result = super.applyMoveTo(value + metrics.correctionOffset);
    assert(result); // since we tried to pass an in-range value, it shouldn't ever overflow
    return !done;
  }

  @override
  String toString() {
1726
    return '${objectRuntimeType(this, '_NestedOuterBallisticScrollActivity')}(${metrics.minRange} .. ${metrics.maxRange}; correcting by ${metrics.correctionOffset})';
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 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770

/// Handle to provide to a [SliverOverlapAbsorber], a [SliverOverlapInjector],
/// and an [NestedScrollViewViewport], to shift overlap in a [NestedScrollView].
///
/// A particular [SliverOverlapAbsorberHandle] can only be assigned to a single
/// [SliverOverlapAbsorber] at a time. It can also be (and normally is) assigned
/// to one or more [SliverOverlapInjector]s, which must be later descendants of
/// the same [NestedScrollViewViewport] as the [SliverOverlapAbsorber]. The
/// [SliverOverlapAbsorber] must be a direct descendant of the
/// [NestedScrollViewViewport], taking part in the same sliver layout. (The
/// [SliverOverlapInjector] can be a descendant that takes part in a nested
/// scroll view's sliver layout.)
///
/// Whenever the [NestedScrollViewViewport] is marked dirty for layout, it will
/// cause its assigned [SliverOverlapAbsorberHandle] to fire notifications. It
/// is the responsibility of the [SliverOverlapInjector]s (and any other
/// clients) to mark themselves dirty when this happens, in case the geometry
/// subsequently changes during layout.
///
/// See also:
///
///  * [NestedScrollView], which uses a [NestedScrollViewViewport] and a
///    [SliverOverlapAbsorber] to align its children, and which shows sample
///    usage for this class.
class SliverOverlapAbsorberHandle extends ChangeNotifier {
  // Incremented when a RenderSliverOverlapAbsorber takes ownership of this
  // object, decremented when it releases it. This allows us to find cases where
  // the same handle is being passed to two render objects.
  int _writers = 0;

  /// The current amount of overlap being absorbed by the
  /// [SliverOverlapAbsorber].
  ///
  /// This corresponds to the [SliverGeometry.layoutExtent] of the child of the
  /// [SliverOverlapAbsorber].
  ///
  /// This is updated during the layout of the [SliverOverlapAbsorber]. It
  /// should not change at any other time. No notifications are sent when it
  /// changes; clients (e.g. [SliverOverlapInjector]s) are responsible for
  /// marking themselves dirty whenever this object sends notifications, which
  /// happens any time the [SliverOverlapAbsorber] might subsequently change the
  /// value during that layout.
1771 1772
  double? get layoutExtent => _layoutExtent;
  double? _layoutExtent;
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785

  /// The total scroll extent of the gap being absorbed by the
  /// [SliverOverlapAbsorber].
  ///
  /// This corresponds to the [SliverGeometry.scrollExtent] of the child of the
  /// [SliverOverlapAbsorber].
  ///
  /// This is updated during the layout of the [SliverOverlapAbsorber]. It
  /// should not change at any other time. No notifications are sent when it
  /// changes; clients (e.g. [SliverOverlapInjector]s) are responsible for
  /// marking themselves dirty whenever this object sends notifications, which
  /// happens any time the [SliverOverlapAbsorber] might subsequently change the
  /// value during that layout.
1786 1787
  double? get scrollExtent => _scrollExtent;
  double? _scrollExtent;
1788

1789
  void _setExtents(double? layoutValue, double? scrollValue) {
1790 1791 1792 1793
    assert(
      _writers == 1,
      'Multiple RenderSliverOverlapAbsorbers have been provided the same SliverOverlapAbsorberHandle.',
    );
1794 1795 1796 1797 1798 1799 1800 1801
    _layoutExtent = layoutValue;
    _scrollExtent = scrollValue;
  }

  void _markNeedsLayout() => notifyListeners();

  @override
  String toString() {
1802
    String? extra;
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
    switch (_writers) {
      case 0:
        extra = ', orphan';
        break;
      case 1:
        // normal case
        break;
      default:
        extra = ', $_writers WRITERS ASSIGNED';
        break;
    }
1814
    return '${objectRuntimeType(this, 'SliverOverlapAbsorberHandle')}($layoutExtent$extra)';
1815 1816 1817 1818 1819 1820
  }
}

/// A sliver that wraps another, forcing its layout extent to be treated as
/// overlap.
///
1821
/// The difference between the overlap requested by the child `sliver` and the
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
/// overlap reported by this widget, called the _absorbed overlap_, is reported
/// to the [SliverOverlapAbsorberHandle], which is typically passed to a
/// [SliverOverlapInjector].
///
/// See also:
///
///  * [NestedScrollView], whose documentation has sample code showing how to
///    use this widget.
class SliverOverlapAbsorber extends SingleChildRenderObjectWidget {
  /// Creates a sliver that absorbs overlap and reports it to a
  /// [SliverOverlapAbsorberHandle].
  ///
  /// The [handle] must not be null.
  const SliverOverlapAbsorber({
1836 1837 1838
    Key? key,
    required this.handle,
    Widget? sliver,
1839
  }) : assert(handle != null),
1840
      super(key: key, child: sliver);
1841 1842 1843 1844 1845 1846 1847 1848 1849

  /// The object in which the absorbed overlap is recorded.
  ///
  /// A particular [SliverOverlapAbsorberHandle] can only be assigned to a
  /// single [SliverOverlapAbsorber] at a time.
  final SliverOverlapAbsorberHandle handle;

  @override
  RenderSliverOverlapAbsorber createRenderObject(BuildContext context) {
1850
    return RenderSliverOverlapAbsorber(
1851 1852 1853 1854 1855 1856
      handle: handle,
    );
  }

  @override
  void updateRenderObject(BuildContext context, RenderSliverOverlapAbsorber renderObject) {
1857
    renderObject.handle = handle;
1858 1859 1860
  }

  @override
1861 1862
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
1863
    properties.add(DiagnosticsProperty<SliverOverlapAbsorberHandle>('handle', handle));
1864 1865 1866 1867 1868 1869
  }
}

/// A sliver that wraps another, forcing its layout extent to be treated as
/// overlap.
///
1870
/// The difference between the overlap requested by the child `sliver` and the
1871 1872 1873 1874 1875 1876 1877 1878 1879
/// overlap reported by this widget, called the _absorbed overlap_, is reported
/// to the [SliverOverlapAbsorberHandle], which is typically passed to a
/// [RenderSliverOverlapInjector].
class RenderSliverOverlapAbsorber extends RenderSliver with RenderObjectWithChildMixin<RenderSliver> {
  /// Create a sliver that absorbs overlap and reports it to a
  /// [SliverOverlapAbsorberHandle].
  ///
  /// The [handle] must not be null.
  ///
1880
  /// The [sliver] must be a [RenderSliver].
1881
  RenderSliverOverlapAbsorber({
1882 1883
    required SliverOverlapAbsorberHandle handle,
    RenderSliver? sliver,
1884 1885
  }) : assert(handle != null),
       _handle = handle {
1886
    child = sliver;
1887 1888
  }

1889 1890 1891 1892
  /// The object in which the absorbed overlap is recorded.
  ///
  /// A particular [SliverOverlapAbsorberHandle] can only be assigned to a
  /// single [RenderSliverOverlapAbsorber] at a time.
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
  SliverOverlapAbsorberHandle get handle => _handle;
  SliverOverlapAbsorberHandle _handle;
  set handle(SliverOverlapAbsorberHandle value) {
    assert(value != null);
    if (handle == value)
      return;
    if (attached) {
      handle._writers -= 1;
      value._writers += 1;
      value._setExtents(handle.layoutExtent, handle.scrollExtent);
    }
    _handle = value;
  }

  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    handle._writers += 1;
  }

  @override
  void detach() {
    handle._writers -= 1;
    super.detach();
  }

  @override
  void performLayout() {
1921 1922 1923 1924
    assert(
      handle._writers == 1,
      'A SliverOverlapAbsorberHandle cannot be passed to multiple RenderSliverOverlapAbsorber objects at the same time.',
    );
1925
    if (child == null) {
1926
      geometry = SliverGeometry.zero;
1927 1928
      return;
    }
1929 1930
    child!.layout(constraints, parentUsesSize: true);
    final SliverGeometry childLayoutGeometry = child!.geometry!;
1931
    geometry = SliverGeometry(
1932 1933 1934
      scrollExtent: childLayoutGeometry.scrollExtent - childLayoutGeometry.maxScrollObstructionExtent,
      paintExtent: childLayoutGeometry.paintExtent,
      paintOrigin: childLayoutGeometry.paintOrigin,
1935
      layoutExtent: math.max(0, childLayoutGeometry.paintExtent - childLayoutGeometry.maxScrollObstructionExtent),
1936 1937 1938 1939 1940 1941 1942
      maxPaintExtent: childLayoutGeometry.maxPaintExtent,
      maxScrollObstructionExtent: childLayoutGeometry.maxScrollObstructionExtent,
      hitTestExtent: childLayoutGeometry.hitTestExtent,
      visible: childLayoutGeometry.visible,
      hasVisualOverflow: childLayoutGeometry.hasVisualOverflow,
      scrollOffsetCorrection: childLayoutGeometry.scrollOffsetCorrection,
    );
1943 1944 1945 1946
    handle._setExtents(
      childLayoutGeometry.maxScrollObstructionExtent,
      childLayoutGeometry.maxScrollObstructionExtent,
    );
1947 1948 1949 1950 1951 1952 1953 1954
  }

  @override
  void applyPaintTransform(RenderObject child, Matrix4 transform) {
    // child is always at our origin
  }

  @override
1955
  bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
1956
    if (child != null)
1957
      return child!.hitTest(
1958 1959 1960 1961
        result,
        mainAxisPosition: mainAxisPosition,
        crossAxisPosition: crossAxisPosition,
      );
1962 1963 1964 1965 1966 1967
    return false;
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    if (child != null)
1968
      context.paintChild(child!, offset);
1969 1970 1971
  }

  @override
1972 1973
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
1974
    properties.add(DiagnosticsProperty<SliverOverlapAbsorberHandle>('handle', handle));
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
  }
}

/// A sliver that has a sliver geometry based on the values stored in a
/// [SliverOverlapAbsorberHandle].
///
/// The [SliverOverlapAbsorber] must be an earlier descendant of a common
/// ancestor [Viewport], so that it will always be laid out before the
/// [SliverOverlapInjector] during a particular frame.
///
/// See also:
///
///  * [NestedScrollView], which uses a [SliverOverlapAbsorber] to align its
///    children, and which shows sample usage for this class.
class SliverOverlapInjector extends SingleChildRenderObjectWidget {
  /// Creates a sliver that is as tall as the value of the given [handle]'s
  /// layout extent.
  ///
  /// The [handle] must not be null.
  const SliverOverlapInjector({
1995 1996 1997
    Key? key,
    required this.handle,
    Widget? sliver,
1998
  }) : assert(handle != null),
1999
       super(key: key, child: sliver);
2000 2001 2002 2003 2004 2005 2006 2007 2008

  /// The handle to the [SliverOverlapAbsorber] that is feeding this injector.
  ///
  /// This should be a handle owned by a [SliverOverlapAbsorber] and a
  /// [NestedScrollViewViewport].
  final SliverOverlapAbsorberHandle handle;

  @override
  RenderSliverOverlapInjector createRenderObject(BuildContext context) {
2009
    return RenderSliverOverlapInjector(
2010 2011 2012 2013 2014 2015
      handle: handle,
    );
  }

  @override
  void updateRenderObject(BuildContext context, RenderSliverOverlapInjector renderObject) {
2016
    renderObject.handle = handle;
2017 2018 2019
  }

  @override
2020 2021
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
2022
    properties.add(DiagnosticsProperty<SliverOverlapAbsorberHandle>('handle', handle));
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
  }
}

/// A sliver that has a sliver geometry based on the values stored in a
/// [SliverOverlapAbsorberHandle].
///
/// The [RenderSliverOverlapAbsorber] must be an earlier descendant of a common
/// ancestor [RenderViewport] (probably a [RenderNestedScrollViewViewport]), so
/// that it will always be laid out before the [RenderSliverOverlapInjector]
/// during a particular frame.
class RenderSliverOverlapInjector extends RenderSliver {
  /// Creates a sliver that is as tall as the value of the given [handle]'s extent.
  ///
  /// The [handle] must not be null.
  RenderSliverOverlapInjector({
2038
    required SliverOverlapAbsorberHandle handle,
2039 2040
  }) : assert(handle != null),
       _handle = handle;
2041

2042 2043
  double? _currentLayoutExtent;
  double? _currentMaxExtent;
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086

  /// The object that specifies how wide to make the gap injected by this render
  /// object.
  ///
  /// This should be a handle owned by a [RenderSliverOverlapAbsorber] and a
  /// [RenderNestedScrollViewViewport].
  SliverOverlapAbsorberHandle get handle => _handle;
  SliverOverlapAbsorberHandle _handle;
  set handle(SliverOverlapAbsorberHandle value) {
    assert(value != null);
    if (handle == value)
      return;
    if (attached) {
      handle.removeListener(markNeedsLayout);
    }
    _handle = value;
    if (attached) {
      handle.addListener(markNeedsLayout);
      if (handle.layoutExtent != _currentLayoutExtent ||
          handle.scrollExtent != _currentMaxExtent)
        markNeedsLayout();
    }
  }

  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    handle.addListener(markNeedsLayout);
    if (handle.layoutExtent != _currentLayoutExtent ||
        handle.scrollExtent != _currentMaxExtent)
      markNeedsLayout();
  }

  @override
  void detach() {
    handle.removeListener(markNeedsLayout);
    super.detach();
  }

  @override
  void performLayout() {
    _currentLayoutExtent = handle.layoutExtent;
    _currentMaxExtent = handle.layoutExtent;
2087
    final double clampedLayoutExtent = math.min(
2088
      _currentLayoutExtent! - constraints.scrollOffset,
2089 2090
      constraints.remainingPaintExtent,
    );
2091
    geometry = SliverGeometry(
2092
      scrollExtent: _currentLayoutExtent!,
2093
      paintExtent: math.max(0.0, clampedLayoutExtent),
2094
      maxPaintExtent: _currentMaxExtent!,
2095 2096 2097 2098 2099 2100 2101
    );
  }

  @override
  void debugPaint(PaintingContext context, Offset offset) {
    assert(() {
      if (debugPaintSizeEnabled) {
2102
        final Paint paint = Paint()
2103 2104 2105 2106 2107 2108 2109
          ..color = const Color(0xFFCC9933)
          ..strokeWidth = 3.0
          ..style = PaintingStyle.stroke;
        Offset start, end, delta;
        switch (constraints.axis) {
          case Axis.vertical:
            final double x = offset.dx + constraints.crossAxisExtent / 2.0;
2110
            start = Offset(x, offset.dy);
2111
            end = Offset(x, offset.dy + geometry!.paintExtent);
2112
            delta = Offset(constraints.crossAxisExtent / 5.0, 0.0);
2113 2114 2115
            break;
          case Axis.horizontal:
            final double y = offset.dy + constraints.crossAxisExtent / 2.0;
2116
            start = Offset(offset.dx, y);
2117
            end = Offset(offset.dy + geometry!.paintExtent, y);
2118
            delta = Offset(0.0, constraints.crossAxisExtent / 5.0);
2119 2120 2121
            break;
        }
        for (int index = -2; index <= 2; index += 1) {
2122 2123 2124 2125 2126 2127 2128 2129
          paintZigZag(
            context.canvas,
            paint,
            start - delta * index.toDouble(),
            end - delta * index.toDouble(),
            10,
            10.0,
          );
2130 2131 2132 2133 2134 2135 2136
        }
      }
      return true;
    }());
  }

  @override
2137 2138
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
2139
    properties.add(DiagnosticsProperty<SliverOverlapAbsorberHandle>('handle', handle));
2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
  }
}

/// The [Viewport] variant used by [NestedScrollView].
///
/// This viewport takes a [SliverOverlapAbsorberHandle] and notifies it any time
/// the viewport needs to recompute its layout (e.g. when it is scrolled).
class NestedScrollViewViewport extends Viewport {
  /// Creates a variant of [Viewport] that has a [SliverOverlapAbsorberHandle].
  ///
  /// The [handle] must not be null.
  NestedScrollViewViewport({
2152
    Key? key,
2153
    AxisDirection axisDirection = AxisDirection.down,
2154
    AxisDirection? crossAxisDirection,
2155
    double anchor = 0.0,
2156 2157
    required ViewportOffset offset,
    Key? center,
2158
    List<Widget> slivers = const <Widget>[],
2159
    required this.handle,
2160
    Clip clipBehavior = Clip.hardEdge,
2161 2162 2163 2164 2165 2166 2167 2168 2169
  }) : assert(handle != null),
       super(
         key: key,
         axisDirection: axisDirection,
         crossAxisDirection: crossAxisDirection,
         anchor: anchor,
         offset: offset,
         center: center,
         slivers: slivers,
2170
         clipBehavior: clipBehavior,
2171 2172 2173 2174 2175 2176 2177
       );

  /// The handle to the [SliverOverlapAbsorber] that is feeding this injector.
  final SliverOverlapAbsorberHandle handle;

  @override
  RenderNestedScrollViewViewport createRenderObject(BuildContext context) {
2178
    return RenderNestedScrollViewViewport(
2179
      axisDirection: axisDirection,
2180 2181 2182 2183
      crossAxisDirection: crossAxisDirection ?? Viewport.getDefaultCrossAxisDirection(
        context,
        axisDirection,
      ),
2184 2185 2186
      anchor: anchor,
      offset: offset,
      handle: handle,
2187
      clipBehavior: clipBehavior,
2188 2189 2190 2191 2192 2193 2194
    );
  }

  @override
  void updateRenderObject(BuildContext context, RenderNestedScrollViewViewport renderObject) {
    renderObject
      ..axisDirection = axisDirection
2195 2196 2197 2198
      ..crossAxisDirection = crossAxisDirection ?? Viewport.getDefaultCrossAxisDirection(
        context,
        axisDirection,
      )
2199 2200
      ..anchor = anchor
      ..offset = offset
2201 2202
      ..handle = handle
      ..clipBehavior = clipBehavior;
2203 2204 2205
  }

  @override
2206 2207
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
2208
    properties.add(DiagnosticsProperty<SliverOverlapAbsorberHandle>('handle', handle));
2209 2210 2211 2212 2213 2214 2215 2216
  }
}

/// The [RenderViewport] variant used by [NestedScrollView].
///
/// This viewport takes a [SliverOverlapAbsorberHandle] and notifies it any time
/// the viewport needs to recompute its layout (e.g. when it is scrolled).
class RenderNestedScrollViewViewport extends RenderViewport {
2217 2218
  /// Create a variant of [RenderViewport] that has a
  /// [SliverOverlapAbsorberHandle].
2219 2220 2221
  ///
  /// The [handle] must not be null.
  RenderNestedScrollViewViewport({
2222
    AxisDirection axisDirection = AxisDirection.down,
2223 2224
    required AxisDirection crossAxisDirection,
    required ViewportOffset offset,
2225
    double anchor = 0.0,
2226 2227 2228
    List<RenderSliver>? children,
    RenderSliver? center,
    required SliverOverlapAbsorberHandle handle,
2229
    Clip clipBehavior = Clip.hardEdge,
2230 2231 2232 2233 2234 2235 2236 2237 2238
  }) : assert(handle != null),
       _handle = handle,
       super(
         axisDirection: axisDirection,
         crossAxisDirection: crossAxisDirection,
         offset: offset,
         anchor: anchor,
         children: children,
         center: center,
2239
         clipBehavior: clipBehavior,
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
       );

  /// The object to notify when [markNeedsLayout] is called.
  SliverOverlapAbsorberHandle get handle => _handle;
  SliverOverlapAbsorberHandle _handle;
  /// Setting this will trigger notifications on the new object.
  set handle(SliverOverlapAbsorberHandle value) {
    assert(value != null);
    if (handle == value)
      return;
    _handle = value;
    handle._markNeedsLayout();
  }

  @override
  void markNeedsLayout() {
    handle._markNeedsLayout();
    super.markNeedsLayout();
  }

  @override
2261 2262
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
2263
    properties.add(DiagnosticsProperty<SliverOverlapAbsorberHandle>('handle', handle));
2264 2265
  }
}