-
-
Notifications
You must be signed in to change notification settings - Fork 120
/
extended_nested_scroll_view.dart
1768 lines (1628 loc) · 63.6 KB
/
extended_nested_scroll_view.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
104
105
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ignore_for_file: unnecessary_cast
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../extended_nested_scroll_view.dart';
part 'extended_nested_scroll_view_part.dart';
// ignore_for_file: unnecessary_null_comparison, always_put_control_body_on_new_line
/// 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
/// flexible [SliverAppBar] containing a [TabBar] in the header (built by
/// [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
/// the outer [ScrollView]. For example, flinging the inner list to scroll to
/// 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.
///
/// {@tool sample --template=stateless_widget_material}
///
/// This example shows a [ExtendedNestedScrollView] 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
/// Widget build(BuildContext context) {
/// final List<String> _tabs = <String>['Tab 1', 'Tab 2'];
/// return DefaultTabController(
/// length: _tabs.length, // This is the number of tabs.
/// 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(),
/// ),
/// ),
/// ),
/// ];
/// },
/// 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,
/// ),
/// ),
/// ),
/// ],
/// );
/// },
/// ),
/// );
/// }).toList(),
/// ),
/// ),
/// ),
/// );
/// }
/// ```
/// {@end-tool}
///
/// ## [SliverAppBar]s with [ExtendedNestedScrollView]s
///
/// Using a [SliverAppBar] in the outer scroll view, or [headerSliverBuilder],
/// of a [ExtendedNestedScrollView] 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.
///
/// This works naturally in a [NestedScrollView], as the pinned [SliverAppBar]
/// 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 [ExtendedNestedScrollView.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.
///
/// {@tool dartpad}
/// 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.
///
/// ** See code in examples/api/lib/widgets/nested_scroll_view/nested_scroll_view.1.dart **
/// {@end-tool}
///
/// ### Snapping [SliverAppBar]s
///
/// Floating [SliverAppBar]s also have the option to perform a snapping animation.
/// 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.
///
/// {@tool dartpad}
/// This simple example shows a [NestedScrollView] whose header contains a
/// snapping, floating [SliverAppBar]. _Without_ setting any additional flags,
/// 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.
///
/// ** See code in examples/api/lib/widgets/nested_scroll_view/nested_scroll_view.2.dart **
/// {@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
///
// See https://github.com/flutter/flutter/issues/54059
/// 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].
class ExtendedNestedScrollView extends StatefulWidget {
/// Creates a nested scroll view.
///
/// The [reverse], [headerSliverBuilder], and [body] arguments must not be
/// null.
const ExtendedNestedScrollView({
super.key,
this.controller,
this.scrollDirection = Axis.vertical,
this.reverse = false,
this.physics,
required this.headerSliverBuilder,
required this.body,
this.dragStartBehavior = DragStartBehavior.start,
this.floatHeaderSlivers = false,
this.clipBehavior = Clip.hardEdge,
this.restorationId,
this.scrollBehavior,
this.pinnedHeaderSliverHeightBuilder,
this.onlyOneScrollInBody = false,
this.keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
}) : assert(scrollDirection != null),
assert(reverse != null),
assert(headerSliverBuilder != null),
assert(body != null),
assert(floatHeaderSlivers != null),
assert(clipBehavior != null);
/// Get the total height of pinned header in NestedScrollView header.
final NestedScrollViewPinnedHeaderSliverHeightBuilder?
pinnedHeaderSliverHeightBuilder;
/// When [ExtendedNestedScrollView]'s body has [TabBarView]/[PageView] and
/// their children have AutomaticKeepAliveClientMixin or PageStorageKey,
/// [_innerController.nestedPositions] will have more one,
/// will scroll all of scroll positions together.
/// set [onlyOneScrollInBody] true to avoid it.
final bool onlyOneScrollInBody;
/// An object that can be used to control the position to which the outer
/// scroll view is scrolled.
final ScrollController? controller;
/// {@macro flutter.widgets.scroll_view.scrollDirection}
///
/// This property only applies to the [Axis] of the outer scroll view,
/// composed of the slivers returned from [headerSliverBuilder]. Since the
/// inner scroll view is not directly configured by the [NestedScrollView],
/// for the axes to match, configure the scroll view of the [body] the same
/// way if they are expected to scroll in the same orientation. This allows
/// for flexible configurations of the NestedScrollView.
final Axis scrollDirection;
/// 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.
///
/// This property only applies to the outer scroll view, composed of the
/// slivers returned from [headerSliverBuilder]. Since the inner scroll view
/// is not directly configured by the [NestedScrollView]. For both to scroll
/// in reverse, configure the scroll view of the [body] the same way if they
/// are expected to match. This allows for flexible configurations of the
/// NestedScrollView.
///
/// Defaults to false.
final bool reverse;
/// How the scroll view should respond to user input.
///
/// For example, determines how the scroll view continues to animate after the
/// user stops dragging the scroll view (providing a custom implementation of
/// [ScrollPhysics.createBallisticSimulation] allows this particular aspect of
/// the physics to be overridden).
///
/// If an explicit [ScrollBehavior] is provided to [scrollBehavior], the
/// [ScrollPhysics] provided by that behavior will take precedence after
/// [physics].
///
/// Defaults to matching platform conventions.
///
/// 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.
///
/// This property only applies to the outer scroll view, composed of the
/// slivers returned from [headerSliverBuilder]. Since the inner scroll view
/// is not directly configured by the [NestedScrollView]. For both to scroll
/// with the same [ScrollPhysics], configure the scroll view of the [body]
/// the same way if they are expected to match, or use a [ScrollBehavior] as
/// an ancestor so both the inner and outer scroll views inherit the same
/// [ScrollPhysics]. This allows for flexible configurations of the
/// NestedScrollView.
///
/// The [ScrollPhysics] also determine whether or not the [NestedScrollView]
/// can accept input from the user to change the scroll offset. For example,
/// [NeverScrollableScrollPhysics] typically will not allow the user to drag a
/// scroll view, but in this case, if one of the two scroll views can be
/// dragged, then dragging will be allowed. Configuring both scroll views with
/// [NeverScrollableScrollPhysics] will disallow dragging in this case.
final ScrollPhysics? physics;
/// 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].
final NestedScrollViewHeaderSliversBuilder headerSliverBuilder;
/// The widget to show inside the [NestedScrollView].
///
/// Typically this will be [TabBarView].
///
/// The [body] is built in a context that provides a [PrimaryScrollController]
/// 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].
final Widget body;
/// {@macro flutter.widgets.scrollable.dragStartBehavior}
final DragStartBehavior dragStartBehavior;
/// 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.
final bool floatHeaderSlivers;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
final Clip clipBehavior;
/// {@macro flutter.widgets.scrollable.restorationId}
final String? restorationId;
/// {@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;
/// {@template flutter.widgets.scroll_view.keyboardDismissBehavior}
/// [ScrollViewKeyboardDismissBehavior] the defines how this [ScrollView] will
/// dismiss the keyboard automatically.
/// {@endtemplate}
final ScrollViewKeyboardDismissBehavior keyboardDismissBehavior;
/// 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.
static SliverOverlapAbsorberHandle sliverOverlapAbsorberHandleFor(
BuildContext context) {
final _InheritedNestedScrollView? target = context
.dependOnInheritedWidgetOfExactType<_InheritedNestedScrollView>();
assert(
target != null,
'NestedScrollView.sliverOverlapAbsorberHandleFor must be called with a context that contains a NestedScrollView.',
);
return target!.state._absorberHandle;
}
List<Widget> _buildSlivers(BuildContext context,
ScrollController innerController, bool bodyIsScrolled) {
return <Widget>[
...headerSliverBuilder(context, bodyIsScrolled),
_ExtendedSliverFillRemainingWithScrollable(
// The inner (body) scroll view must use this scroll controller so that
// the independent scroll positions can be kept in sync.
child: PrimaryScrollController(
// The inner scroll view should always inherit this
// PrimaryScrollController, on every platform.
automaticallyInheritForPlatforms: TargetPlatform.values.toSet(),
// `PrimaryScrollController.scrollDirection` is not set, and so it is
// restricted to the default Axis.vertical.
// Ideally the inner and outer views would have the same
// scroll direction, and so we could assume
// `NestedScrollView.scrollDirection` for the PrimaryScrollController,
// but use cases already exist where the axes are mismatched.
// https://github.com/flutter/flutter/issues/102001
controller: innerController,
child: body,
),
),
];
}
@override
ExtendedNestedScrollViewState createState() =>
ExtendedNestedScrollViewState();
}
/// 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).
///
/// {@tool dartpad}
/// [NestedScrollViewState] can be obtained using a [GlobalKey].
/// Using the following setup, you can access the inner scroll controller
/// using `globalKey.currentState.innerController`.
///
/// ** See code in examples/api/lib/widgets/nested_scroll_view/nested_scroll_view_state.0.dart **
/// {@end-tool}
class ExtendedNestedScrollViewState extends State<ExtendedNestedScrollView> {
final SliverOverlapAbsorberHandle _absorberHandle =
SliverOverlapAbsorberHandle();
/// 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
/// sliver(s) contained in [NestedScrollView.headerSliverBuilder].
ScrollController get innerController => _coordinator!._innerController;
/// 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].
ScrollController get outerController => _coordinator!._outerController;
/// The positions of [innerController] which are influenced by [onlyOneScrollInBody]
/// [innerController.positions] are all of positions
/// [innerPositions] is single one when [onlyOneScrollInBody] is true.
Iterable<ScrollPosition> get innerPositions => _coordinator!._innerPositions;
_ExtendedNestedScrollCoordinator? _coordinator;
@override
void initState() {
super.initState();
_coordinator = _ExtendedNestedScrollCoordinator(
this,
widget.controller,
_handleHasScrolledBodyChanged,
widget.floatHeaderSlivers,
widget.pinnedHeaderSliverHeightBuilder,
widget.onlyOneScrollInBody,
widget.scrollDirection,
);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_coordinator!.setParent(widget.controller);
}
@override
void didUpdateWidget(ExtendedNestedScrollView oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller)
_coordinator!.setParent(widget.controller);
}
@override
void dispose() {
_coordinator!.dispose();
_coordinator = null;
_absorberHandle.dispose();
super.dispose();
}
bool? _lastHasScrolledBody;
void _handleHasScrolledBodyChanged() {
if (!mounted) {
return;
}
final bool newHasScrolledBody = _coordinator!.hasScrolledBody;
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.)
});
}
}
@override
Widget build(BuildContext context) {
final ScrollPhysics _scrollPhysics =
widget.physics?.applyTo(const ClampingScrollPhysics()) ??
widget.scrollBehavior
?.getScrollPhysics(context)
.applyTo(const ClampingScrollPhysics()) ??
const ClampingScrollPhysics();
return _InheritedNestedScrollView(
state: this,
child: Builder(
builder: (BuildContext context) {
_lastHasScrolledBody = _coordinator!.hasScrolledBody;
return _NestedScrollViewCustomScrollView(
dragStartBehavior: widget.dragStartBehavior,
scrollDirection: widget.scrollDirection,
reverse: widget.reverse,
physics: _scrollPhysics,
scrollBehavior: widget.scrollBehavior ??
ScrollConfiguration.of(context).copyWith(scrollbars: false),
controller: _coordinator!._outerController,
slivers: widget._buildSlivers(
context,
_coordinator!._innerController,
_lastHasScrolledBody!,
),
handle: _absorberHandle,
clipBehavior: widget.clipBehavior,
restorationId: widget.restorationId,
keyboardDismissBehavior: widget.keyboardDismissBehavior,
);
},
),
);
}
}
class _NestedScrollViewCustomScrollView extends CustomScrollView {
const _NestedScrollViewCustomScrollView({
required super.scrollDirection,
required super.reverse,
required super.physics,
required super.scrollBehavior,
required super.controller,
required super.slivers,
required this.handle,
required super.clipBehavior,
super.dragStartBehavior,
super.restorationId,
super.keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
});
final SliverOverlapAbsorberHandle handle;
@override
Widget buildViewport(
BuildContext context,
ViewportOffset offset,
AxisDirection axisDirection,
List<Widget> slivers,
) {
assert(!shrinkWrap);
return NestedScrollViewViewport(
axisDirection: axisDirection,
offset: offset,
slivers: slivers,
handle: handle,
clipBehavior: clipBehavior,
);
}
}
class _InheritedNestedScrollView extends InheritedWidget {
const _InheritedNestedScrollView({
required this.state,
required super.child,
}) : assert(state != null),
assert(child != null);
final ExtendedNestedScrollViewState state;
@override
bool updateShouldNotify(_InheritedNestedScrollView old) => state != old.state;
}
class _NestedScrollMetrics extends FixedScrollMetrics {
_NestedScrollMetrics({
required super.minScrollExtent,
required super.maxScrollExtent,
required super.pixels,
required super.viewportDimension,
required super.axisDirection,
required super.devicePixelRatio,
required this.minRange,
required this.maxRange,
required this.correctionOffset,
});
@override
_NestedScrollMetrics copyWith({
double? minScrollExtent,
double? maxScrollExtent,
double? pixels,
double? viewportDimension,
AxisDirection? axisDirection,
double? devicePixelRatio,
double? minRange,
double? maxRange,
double? correctionOffset,
}) {
return _NestedScrollMetrics(
minScrollExtent: minScrollExtent ??
(hasContentDimensions ? this.minScrollExtent : null),
maxScrollExtent: maxScrollExtent ??
(hasContentDimensions ? this.maxScrollExtent : null),
pixels: pixels ?? (hasPixels ? this.pixels : null),
viewportDimension: viewportDimension ??
(hasViewportDimension ? this.viewportDimension : null),
axisDirection: axisDirection ?? this.axisDirection,
devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio,
minRange: minRange ?? this.minRange,
maxRange: maxRange ?? this.maxRange,
correctionOffset: correctionOffset ?? this.correctionOffset,
);
}
final double minRange;
final double maxRange;
final double correctionOffset;
}
typedef _NestedScrollActivityGetter = ScrollActivity Function(
_NestedScrollPosition position);
class _NestedScrollCoordinator
implements ScrollActivityDelegate, ScrollHoldController {
_NestedScrollCoordinator(
this._state,
this._parent,
this._onHasScrolledBodyChanged,
this._floatHeaderSlivers,
) {
final double initialScrollOffset = _parent?.initialScrollOffset ?? 0.0;
_outerController = _NestedScrollController(
this,
initialScrollOffset: initialScrollOffset,
debugLabel: 'outer',
);
_innerController = _NestedScrollController(
this,
debugLabel: 'inner',
);
}
final ExtendedNestedScrollViewState _state;
ScrollController? _parent;
final VoidCallback _onHasScrolledBodyChanged;
final bool _floatHeaderSlivers;
late _NestedScrollController _outerController;
late _NestedScrollController _innerController;
_NestedScrollPosition? get _outerPosition {
if (!_outerController.hasClients) {
return null;
}
return _outerController.nestedPositions.single;
}
Iterable<_NestedScrollPosition> get _innerPositions {
return _innerController.nestedPositions;
}
bool get canScrollBody {
final _NestedScrollPosition? outer = _outerPosition;
if (outer == null) {
return true;
}
return outer.haveDimensions && outer.extentAfter == 0.0;
}
bool get hasScrolledBody {
for (final _NestedScrollPosition position in _innerPositions) {
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) {
return true;
}
}
return false;
}
void updateShadow() {
_onHasScrolledBodyChanged();
}
ScrollDirection get userScrollDirection => _userScrollDirection;
ScrollDirection _userScrollDirection = ScrollDirection.idle;
void updateUserScrollDirection(ScrollDirection value) {
if (userScrollDirection == value) {
return;
}
_userScrollDirection = value;
_outerPosition!.didUpdateScrollDirection(value);
for (final _NestedScrollPosition position in _innerPositions) {
position.didUpdateScrollDirection(value);
}
}
ScrollDragController? _currentDrag;
void beginActivity(ScrollActivity newOuterActivity,
_NestedScrollActivityGetter innerActivityGetter) {
_outerPosition!.beginActivity(newOuterActivity);
bool scrolling = newOuterActivity.isScrolling;
for (final _NestedScrollPosition position in _innerPositions) {
final ScrollActivity newInnerActivity = innerActivityGetter(position);
position.beginActivity(newInnerActivity);
scrolling = scrolling && newInnerActivity.isScrolling;
}
_currentDrag?.dispose();
_currentDrag = null;
if (!scrolling) {
updateUserScrollDirection(ScrollDirection.idle);
}
}
@override
AxisDirection get axisDirection => _outerPosition!.axisDirection;
static IdleScrollActivity _createIdleScrollActivity(
_NestedScrollPosition position) {
return IdleScrollActivity(position);
}
@override
void goIdle() {
beginActivity(
_createIdleScrollActivity(_outerPosition!),
_createIdleScrollActivity,
);
}
@override
void goBallistic(double velocity) {
beginActivity(
createOuterBallisticScrollActivity(velocity),
(_NestedScrollPosition position) {
return createInnerBallisticScrollActivity(
position,
velocity,
);
},
);
}
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.
_NestedScrollPosition? innerPosition;
if (velocity != 0.0) {
for (final _NestedScrollPosition position in _innerPositions) {
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.
return _outerPosition!.createBallisticScrollActivity(
_outerPosition!.physics.createBallisticSimulation(
_outerPosition!,
velocity,
),
mode: _NestedBallisticScrollActivityMode.independent,
);
}
final _NestedScrollMetrics metrics = _getMetrics(innerPosition, velocity);
return _outerPosition!.createBallisticScrollActivity(
_outerPosition!.physics.createBallisticSimulation(metrics, velocity),
mode: _NestedBallisticScrollActivityMode.outer,
metrics: metrics,
);
}
@protected
ScrollActivity createInnerBallisticScrollActivity(
_NestedScrollPosition position, double velocity) {
return position.createBallisticScrollActivity(
position.physics.createBallisticSimulation(
_getMetrics(position, velocity),
velocity,
),
mode: _NestedBallisticScrollActivityMode.inner,
);
}
_NestedScrollMetrics _getMetrics(
_NestedScrollPosition innerPosition, double velocity) {
assert(innerPosition != null);
double pixels, minRange, maxRange, correctionOffset;
double extra = 0.0;
if (innerPosition.pixels == innerPosition.minScrollExtent) {
pixels = clampDouble(
_outerPosition!.pixels,
_outerPosition!.minScrollExtent,
_outerPosition!.maxScrollExtent,
); // TODO(ianh): gracefully handle out-of-range outer positions
minRange = _outerPosition!.minScrollExtent;
maxRange = _outerPosition!.maxScrollExtent;
assert(minRange <= maxRange);
correctionOffset = 0.0;
} else {
assert(innerPosition.pixels != innerPosition.minScrollExtent);
if (innerPosition.pixels < innerPosition.minScrollExtent) {
pixels = innerPosition.pixels -
innerPosition.minScrollExtent +
_outerPosition!.minScrollExtent;
} else {
assert(innerPosition.pixels > innerPosition.minScrollExtent);
pixels = innerPosition.pixels -
innerPosition.minScrollExtent +
_outerPosition!.maxScrollExtent;
}
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.
extra = _outerPosition!.maxScrollExtent - _outerPosition!.pixels;
assert(extra >= 0.0);
minRange = pixels;
maxRange = pixels + extra;
assert(minRange <= maxRange);
correctionOffset = _outerPosition!.pixels - pixels;
} 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.
extra = _outerPosition!.pixels - _outerPosition!.minScrollExtent;
assert(extra >= 0.0);
minRange = pixels - extra;
maxRange = pixels;
assert(minRange <= maxRange);
correctionOffset = _outerPosition!.pixels - pixels;
} 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
extra = _outerPosition!.minScrollExtent - _outerPosition!.pixels;
} else if (velocity < 0.0) {
// growing
extra = _outerPosition!.pixels -
(_outerPosition!.maxScrollExtent -
_outerPosition!.minScrollExtent);
}
assert(extra <= 0.0);
minRange = _outerPosition!.minScrollExtent;
maxRange = _outerPosition!.maxScrollExtent + extra;
assert(minRange <= maxRange);
correctionOffset = 0.0;
}
}
return _NestedScrollMetrics(
minScrollExtent: _outerPosition!.minScrollExtent,
maxScrollExtent: _outerPosition!.maxScrollExtent +
innerPosition.maxScrollExtent -
innerPosition.minScrollExtent +
extra,
pixels: pixels,
viewportDimension: _outerPosition!.viewportDimension,
axisDirection: _outerPosition!.axisDirection,
minRange: minRange,
maxRange: maxRange,
correctionOffset: correctionOffset,
devicePixelRatio: _outerPosition!.devicePixelRatio,