-
Notifications
You must be signed in to change notification settings - Fork 41
/
preload_page_view.dart
1279 lines (1170 loc) · 47.1 KB
/
preload_page_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
// import 'dart:async';
// import 'dart:math' as math;
// import 'package:flutter/rendering.dart';
// import 'package:flutter/widgets.dart';
// /// A controller for [PreloadPageView].
// ///
// /// A page controller lets you manipulate which page is visible in a [PreloadPageView].
// /// In addition to being able to control the pixel offset of the content inside
// /// the [PreloadPageView], a [PreloadPageController] also lets you control the offset in terms
// /// of pages, which are increments of the viewport size.
// ///
// /// See also:
// ///
// /// * [PreloadPageView], which is the widget this object controls.
// class PreloadPageController extends ScrollController {
// /// Creates a page controller.
// ///
// /// The [initialPage], [keepPage], and [viewportFraction] arguments must not be null.
// PreloadPageController({
// this.initialPage = 0,
// this.keepPage = true,
// this.viewportFraction = 1.0,
// }) : assert(viewportFraction > 0.0);
// /// The page to show when first creating the [PreloadPageView].
// final int initialPage;
// /// Save the current [page] with [PageStorage] and restore it if
// /// this controller's scrollable is recreated.
// ///
// /// If this property is set to false, the current [page] is never saved
// /// and [initialPage] is always used to initialize the scroll offset.
// /// If true (the default), the initial page is used the first time the
// /// controller's scrollable is created, since there's isn't a page to
// /// restore yet. Subsequently the saved page is restored and
// /// [initialPage] is ignored.
// ///
// /// See also:
// ///
// /// * [PageStorageKey], which should be used when more than one
// /// scrollable appears in the same route, to distinguish the [PageStorage]
// /// locations used to save scroll offsets.
// final bool keepPage;
// /// The fraction of the viewport that each page should occupy.
// ///
// /// Defaults to 1.0, which means each page fills the viewport in the scrolling
// /// direction.
// final double viewportFraction;
// /// The current page displayed in the controlled [PreloadPageView].
// ///
// /// There are circumstances that this [PreloadPageController] can't know the current
// /// page. Reading [page] will throw an [AssertionError] in the following cases:
// ///
// /// 1. No [PreloadPageView] is currently using this [PreloadPageController]. Once a
// /// [PreloadPageView] starts using this [PreloadPageController], the new [page]
// /// position will be derived:
// ///
// /// * First, based on the attached [PreloadPageView]'s [BuildContext] and the
// /// position saved at that context's [PageStorage] if [keepPage] is true.
// /// * Second, from the [PreloadPageController]'s [initialPage].
// ///
// /// 2. More than one [PreloadPageView] using the same [PreloadPageController].
// ///
// /// The [hasClients] property can be used to check if a [PreloadPageView] is attached
// /// prior to accessing [page].
// double get page {
// assert(
// positions.isNotEmpty,
// 'PageController.page cannot be accessed before a PageView is built with it.',
// );
// assert(
// positions.length == 1,
// 'The page property cannot be read when multiple PageViews are attached to '
// 'the same PageController.',
// );
// final _PagePosition position = this.position as _PagePosition;
// return position.page;
// }
// /// Animates the controlled [PreloadPageView] from the current page to the given page.
// ///
// /// The animation lasts for the given duration and follows the given curve.
// /// The returned [Future] resolves when the animation completes.
// ///
// /// The `duration` and `curve` arguments must not be null.
// Future<void> animateToPage(
// int page, {
// required Duration duration,
// required Curve curve,
// }) {
// final _PagePosition position = this.position as _PagePosition;
// return position.animateTo(
// position.getPixelsFromPage(page.toDouble()),
// duration: duration,
// curve: curve,
// );
// }
// /// Changes which page is displayed in the controlled [PreloadPageView].
// ///
// /// Jumps the page position from its current value to the given value,
// /// without animation, and without checking if the new value is in range.
// void jumpToPage(int page) {
// final _PagePosition position = this.position as _PagePosition;
// position.jumpTo(position.getPixelsFromPage(page.toDouble()));
// }
// /// Animates the controlled [PreloadPageView] to the next page.
// ///
// /// The animation lasts for the given duration and follows the given curve.
// /// The returned [Future] resolves when the animation completes.
// ///
// /// The `duration` and `curve` arguments must not be null.
// Future<void> nextPage({required Duration duration, required Curve curve}) {
// return animateToPage(page.round() + 1, duration: duration, curve: curve);
// }
// /// Animates the controlled [PreloadPageView] to the previous page.
// ///
// /// The animation lasts for the given duration and follows the given curve.
// /// The returned [Future] resolves when the animation completes.
// ///
// /// The `duration` and `curve` arguments must not be null.
// Future<void> previousPage(
// {required Duration duration, required Curve curve}) {
// return animateToPage(page.round() - 1, duration: duration, curve: curve);
// }
// @override
// ScrollPosition createScrollPosition(ScrollPhysics physics,
// ScrollContext context, ScrollPosition? oldPosition) {
// return _PagePosition(
// physics: physics,
// context: context,
// initialPage: initialPage,
// keepPage: keepPage,
// viewportFraction: viewportFraction,
// oldPosition: oldPosition,
// );
// }
// @override
// void attach(ScrollPosition position) {
// super.attach(position);
// final _PagePosition pagePosition = position as _PagePosition;
// pagePosition.viewportFraction = viewportFraction;
// }
// }
// /// Metrics for a [PreloadPageView].
// ///
// /// The metrics are available on [ScrollNotification]s generated from
// /// [PreloadPageView]s.
// class PageMetrics extends FixedScrollMetrics {
// /// Creates an immutable snapshot of values associated with a [PreloadPageView].
// PageMetrics({
// double? minScrollExtent,
// double? maxScrollExtent,
// double? pixels,
// double? viewportDimension,
// required AxisDirection axisDirection,
// required this.viewportFraction,
// }) : super(
// minScrollExtent: minScrollExtent,
// maxScrollExtent: maxScrollExtent,
// pixels: pixels,
// viewportDimension: viewportDimension,
// axisDirection: axisDirection,
// );
// @override
// PageMetrics copyWith({
// double? minScrollExtent,
// double? maxScrollExtent,
// double? pixels,
// double? viewportDimension,
// AxisDirection? axisDirection,
// double? viewportFraction,
// }) {
// return PageMetrics(
// minScrollExtent: minScrollExtent ?? this.minScrollExtent,
// maxScrollExtent: maxScrollExtent ?? this.maxScrollExtent,
// pixels: pixels ?? this.pixels,
// viewportDimension: viewportDimension ?? this.viewportDimension,
// axisDirection: axisDirection ?? this.axisDirection,
// viewportFraction: viewportFraction ?? this.viewportFraction,
// );
// }
// /// The current page displayed in the [PreloadPageView].
// double get page {
// return math.max(0.0, pixels.clamp(minScrollExtent, maxScrollExtent)) /
// math.max(1.0, viewportDimension * viewportFraction);
// }
// /// The fraction of the viewport that each page occupies.
// ///
// /// Used to compute [page] from the current [pixels].
// final double viewportFraction;
// }
// class _PagePosition extends ScrollPositionWithSingleContext
// implements PageMetrics {
// _PagePosition({
// required ScrollPhysics physics,
// required ScrollContext context,
// this.initialPage = 0,
// bool keepPage = true,
// double viewportFraction = 1.0,
// ScrollPosition? oldPosition,
// }) : assert(viewportFraction > 0.0),
// _viewportFraction = viewportFraction,
// _pageToUseOnStartup = initialPage.toDouble(),
// super(
// physics: physics,
// context: context,
// initialPixels: null,
// keepScrollOffset: keepPage,
// oldPosition: oldPosition,
// );
// final int initialPage;
// double _pageToUseOnStartup;
// @override
// double get viewportFraction => _viewportFraction;
// double _viewportFraction;
// set viewportFraction(double value) {
// if (_viewportFraction == value) return;
// final double oldPage = page;
// _viewportFraction = value;
// if (oldPage != null) forcePixels(getPixelsFromPage(oldPage));
// }
// double getPageFromPixels(double pixels, double viewportDimension) {
// if (pixels == null || viewportDimension == null) {
// return null;
// }
// return math.max(0.0, pixels) /
// math.max(1.0, viewportDimension * viewportFraction);
// }
// double getPixelsFromPage(double page) {
// return page *
// (hasViewportDimension ? viewportDimension : 0) *
// viewportFraction;
// }
// @override
// double? get page => hasPixels
// ? getPageFromPixels(
// hasContentDimensions
// ? pixels.clamp(minScrollExtent, maxScrollExtent)
// : null,
// hasViewportDimension ? viewportDimension : null,
// )
// : null;
// @override
// void saveScrollOffset() {
// PageStorage.of(context.storageContext)?.writeState(
// context.storageContext,
// getPageFromPixels(hasPixels ? pixels : null,
// hasViewportDimension ? viewportDimension : null));
// }
// @override
// void restoreScrollOffset() {
// if (hasPixels == true) {
// final double value = PageStorage.of(context.storageContext)
// ?.readState(context.storageContext);
// if (value != null) _pageToUseOnStartup = value;
// }
// }
// @override
// bool applyViewportDimension(double viewportDimension) {
// final double oldViewportDimensions =
// (hasViewportDimension) ? this.viewportDimension : null;
// final bool result = super.applyViewportDimension(viewportDimension);
// final double oldPixels = (hasPixels) ? pixels : null;
// final double page = (oldPixels == null || oldViewportDimensions == 0.0)
// ? _pageToUseOnStartup
// : getPageFromPixels(oldPixels, oldViewportDimensions);
// final double newPixels = page != null ? getPixelsFromPage(page) : null;
// if (newPixels != null && newPixels != oldPixels) {
// correctPixels(newPixels);
// return false;
// }
// return result;
// }
// @override
// PageMetrics copyWith({
// double minScrollExtent,
// double maxScrollExtent,
// double pixels,
// double viewportDimension,
// AxisDirection axisDirection,
// double viewportFraction,
// }) {
// return PageMetrics(
// 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,
// viewportFraction: viewportFraction ?? this.viewportFraction,
// );
// }
// }
// /// Scroll physics used by a [PreloadPageView].
// ///
// /// These physics cause the page view to snap to page boundaries.
// ///
// /// See also:
// ///
// /// * [ScrollPhysics], the base class which defines the API for scrolling
// /// physics.
// /// * [PreloadPageView.physics], which can override the physics used by a page view.
// class PageScrollPhysics extends ScrollPhysics {
// /// Creates physics for a [PreloadPageView].
// const PageScrollPhysics({ScrollPhysics parent}) : super(parent: parent);
// @override
// PageScrollPhysics applyTo(ScrollPhysics ancestor) {
// return PageScrollPhysics(parent: buildParent(ancestor));
// }
// double _getPage(ScrollPosition position) {
// if (position is _PagePosition && position.page != null)
// return position.page;
// return position.pixels / position.viewportDimension;
// }
// double _getPixels(ScrollPosition position, double page) {
// if (position is _PagePosition) return position.getPixelsFromPage(page);
// return page * position.viewportDimension;
// }
// double _getTargetPixels(
// ScrollPosition position, Tolerance tolerance, double velocity) {
// double page = _getPage(position);
// if (velocity < -tolerance.velocity)
// page -= 0.5;
// else if (velocity > tolerance.velocity) page += 0.5;
// return _getPixels(position, page.roundToDouble());
// }
// @override
// Simulation createBallisticSimulation(
// ScrollMetrics position, double velocity) {
// // If we're out of range and not headed back in range, defer to the parent
// // ballistics, which should put us back in range at a page boundary.
// if ((velocity <= 0.0 && position.pixels <= position.minScrollExtent) ||
// (velocity >= 0.0 && position.pixels >= position.maxScrollExtent))
// return super.createBallisticSimulation(position, velocity);
// final Tolerance tolerance = this.tolerance;
// final double target =
// _getTargetPixels(position as ScrollPosition, tolerance, velocity);
// if (target != position.pixels)
// return ScrollSpringSimulation(spring, position.pixels, target, velocity,
// tolerance: tolerance);
// return null;
// }
// @override
// bool get allowImplicitScrolling => false;
// }
// // Having this global (mutable) page controller is a bit of a hack. We need it
// // to plumb in the factory for _PagePosition, but it will end up accumulating
// // a large list of scroll positions. As long as you don't try to actually
// // control the scroll positions, everything should be fine.
// final PreloadPageController _defaultPageController = PreloadPageController();
// const PageScrollPhysics _kPagePhysics = PageScrollPhysics();
// /// A scrollable list that works page by page.
// ///
// /// Each child of a page view is forced to be the same size as the viewport.
// ///
// /// You can use a [PreloadPageController] to control which page is visible in the view.
// /// In addition to being able to control the pixel offset of the content inside
// /// the [PreloadPageView], a [PreloadPageController] also lets you control the offset in terms
// /// of pages, which are increments of the viewport size.
// ///
// /// The [PreloadPageController] can also be used to control the
// /// [PreloadPageController.initialPage], which determines which page is shown when the
// /// [PreloadPageView] is first constructed, and the [PreloadPageController.viewportFraction],
// /// which determines the size of the pages as a fraction of the viewport size.
// ///
// /// See also:
// ///
// /// * [PreloadPageController], which controls which page is visible in the view.
// /// * [SingleChildScrollView], when you need to make a single child scrollable.
// /// * [ListView], for a scrollable list of boxes.
// /// * [GridView], for a scrollable grid of boxes.
// /// * [ScrollNotification] and [NotificationListener], which can be used to watch
// /// the scroll position without using a [ScrollController].
// class PreloadPageView extends StatefulWidget {
// /// Creates a scrollable list that works page by page from an explicit [List]
// /// of widgets.
// ///
// /// This constructor is appropriate for page views with a small number of
// /// children because constructing the [List] requires doing work for every
// /// child that could possibly be displayed in the page view, instead of just
// /// those children that are actually visible.
// PreloadPageView({
// Key key,
// this.scrollDirection = Axis.horizontal,
// this.reverse = false,
// PreloadPageController controller,
// this.physics,
// this.pageSnapping = true,
// this.onPageChanged,
// List<Widget> children = const <Widget>[],
// this.preloadPagesCount = 1,
// }) : controller = controller ?? _defaultPageController,
// childrenDelegate = SliverChildListDelegate(children),
// super(key: key);
// /// Creates a scrollable list that works page by page using widgets that are
// /// created on demand.
// ///
// /// This constructor is appropriate for page views with a large (or infinite)
// /// number of children because the builder is called only for those children
// /// that are actually visible.
// ///
// /// Providing a non-null [itemCount] lets the [PreloadPageView] compute the maximum
// /// scroll extent.
// ///
// /// [itemBuilder] will be called only with indices greater than or equal to
// /// zero and less than [itemCount].
// ///
// /// You can add [preloadPagesCount] for PreloadPageView if you want preload multiple pages
// PreloadPageView.builder({
// Key key,
// this.scrollDirection = Axis.horizontal,
// this.reverse = false,
// PreloadPageController controller,
// this.physics,
// this.pageSnapping = true,
// this.onPageChanged,
// IndexedWidgetBuilder itemBuilder,
// int itemCount,
// this.preloadPagesCount = 1,
// }) : controller = controller ?? _defaultPageController,
// childrenDelegate =
// SliverChildBuilderDelegate(itemBuilder, childCount: itemCount),
// super(key: key);
// /// Creates a scrollable list that works page by page with a custom child
// /// model.
// PreloadPageView.custom({
// Key key,
// this.scrollDirection = Axis.horizontal,
// this.reverse = false,
// PreloadPageController controller,
// this.physics,
// this.pageSnapping = true,
// this.onPageChanged,
// this.childrenDelegate,
// this.preloadPagesCount = 1,
// }) : controller = controller ?? _defaultPageController,
// super(key: key);
// /// The axis along which the page view scrolls.
// ///
// /// Defaults to [Axis.horizontal].
// final Axis scrollDirection;
// /// Whether the page view scrolls in the reading direction.
// ///
// /// For example, if the reading direction is left-to-right and
// /// [scrollDirection] is [Axis.horizontal], then the page 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 page view
// /// scrolls from top to bottom when [reverse] is false and from bottom to top
// /// when [reverse] is true.
// ///
// /// Defaults to false.
// final bool reverse;
// /// An object that can be used to control the position to which this page
// /// view is scrolled.
// final PreloadPageController controller;
// /// How the page view should respond to user input.
// ///
// /// For example, determines how the page view continues to animate after the
// /// user stops dragging the page view.
// ///
// /// The physics are modified to snap to page boundaries using
// /// [PageScrollPhysics] prior to being used.
// ///
// /// Defaults to matching platform conventions.
// final ScrollPhysics physics;
// /// Set to false to disable page snapping, useful for custom scroll behavior.
// final bool pageSnapping;
// /// Called whenever the page in the center of the viewport changes.
// final ValueChanged<int> onPageChanged;
// /// A delegate that provides the children for the [PreloadPageView].
// ///
// /// The [PreloadPageView.custom] constructor lets you specify this delegate
// /// explicitly. The [PreloadPageView] and [PreloadPageView.builder] constructors create a
// /// [childrenDelegate] that wraps the given [List] and [IndexedWidgetBuilder],
// /// respectively.
// final SliverChildDelegate childrenDelegate;
// /// An integer value that determines number pages that will be preloaded.
// ///
// /// [preloadPagesCount] value start from 0, default 1
// final int preloadPagesCount;
// @override
// State<PreloadPageView> createState() =>
// _PreloadPageViewState(preloadPagesCount);
// }
// class _PreloadPageViewState extends State<PreloadPageView> {
// int _lastReportedPage = 0;
// int _preloadPagesCount = 1;
// _PreloadPageViewState(int preloadPagesCount) {
// _validatePreloadPagesCount(preloadPagesCount);
// this._preloadPagesCount = preloadPagesCount;
// }
// @override
// void initState() {
// super.initState();
// _lastReportedPage = widget.controller.initialPage;
// }
// void _validatePreloadPagesCount(int preloadPagesCount) {
// if (preloadPagesCount < 0) {
// throw 'preloadPagesCount cannot be less than 0. Actual value: $preloadPagesCount';
// }
// }
// AxisDirection _getDirection(BuildContext context) {
// switch (widget.scrollDirection) {
// case Axis.horizontal:
// assert(debugCheckHasDirectionality(context));
// final TextDirection textDirection = Directionality.of(context);
// final AxisDirection axisDirection =
// textDirectionToAxisDirection(textDirection);
// return widget.reverse
// ? flipAxisDirection(axisDirection)
// : axisDirection;
// case Axis.vertical:
// return widget.reverse ? AxisDirection.up : AxisDirection.down;
// default:
// return null;
// }
// }
// @override
// Widget build(BuildContext context) {
// final AxisDirection axisDirection = _getDirection(context);
// final ScrollPhysics physics = widget.pageSnapping
// ? _kPagePhysics.applyTo(widget.physics)
// : widget.physics;
// return NotificationListener<ScrollNotification>(
// onNotification: (ScrollNotification notification) {
// if (notification.depth == 0 &&
// widget.onPageChanged != null &&
// notification is ScrollUpdateNotification) {
// final PageMetrics metrics = notification.metrics as PageMetrics;
// final int currentPage = metrics.page.round();
// if (currentPage != _lastReportedPage) {
// _lastReportedPage = currentPage;
// widget.onPageChanged(currentPage);
// }
// }
// return false;
// },
// child: Scrollable(
// axisDirection: axisDirection,
// controller: widget.controller,
// physics: physics,
// viewportBuilder: (BuildContext context, ViewportOffset position) {
// return Viewport(
// cacheExtent: _preloadPagesCount < 1
// ? 0
// : (_preloadPagesCount == 1
// ? 1
// : widget.scrollDirection == Axis.horizontal
// ? MediaQuery.of(context).size.width *
// _preloadPagesCount -
// 1
// : MediaQuery.of(context).size.height *
// _preloadPagesCount -
// 1),
// axisDirection: axisDirection,
// offset: position,
// slivers: <Widget>[
// SliverFillViewport(
// viewportFraction: widget.controller.viewportFraction,
// delegate: widget.childrenDelegate),
// ],
// );
// },
// ),
// );
// }
// @override
// void debugFillProperties(DiagnosticPropertiesBuilder description) {
// super.debugFillProperties(description);
// description
// .add(EnumProperty<Axis>('scrollDirection', widget.scrollDirection));
// description.add(
// FlagProperty('reverse', value: widget.reverse, ifTrue: 'reversed'));
// description.add(DiagnosticsProperty<PreloadPageController>(
// 'controller', widget.controller,
// showName: false));
// description.add(DiagnosticsProperty<ScrollPhysics>(
// 'physics', widget.physics,
// showName: false));
// description.add(FlagProperty('pageSnapping',
// value: widget.pageSnapping, ifFalse: 'snapping disabled'));
// }
// }
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
/// A controller for [PreloadPageView].
///
/// A page controller lets you manipulate which page is visible in a [PreloadPageView].
/// In addition to being able to control the pixel offset of the content inside
/// the [PreloadPageView], a [PreloadPageController] also lets you control the offset in terms
/// of pages, which are increments of the viewport size.
///
/// See also:
///
/// * [PreloadPageView], which is the widget this object controls.
class PreloadPageController extends ScrollController {
/// Creates a page controller.
///
/// The [initialPage], [keepPage], and [viewportFraction] arguments must not be null.
PreloadPageController({
this.initialPage = 0,
this.keepPage = true,
this.viewportFraction = 1.0,
}) : assert(viewportFraction > 0.0);
/// The page to show when first creating the [PreloadPageView].
final int initialPage;
/// Save the current [page] with [PageStorage] and restore it if
/// this controller's scrollable is recreated.
///
/// If this property is set to false, the current [page] is never saved
/// and [initialPage] is always used to initialize the scroll offset.
/// If true (the default), the initial page is used the first time the
/// controller's scrollable is created, since there's isn't a page to
/// restore yet. Subsequently the saved page is restored and
/// [initialPage] is ignored.
///
/// See also:
///
/// * [PageStorageKey], which should be used when more than one
/// scrollable appears in the same route, to distinguish the [PageStorage]
/// locations used to save scroll offsets.
final bool keepPage;
/// The fraction of the viewport that each page should occupy.
///
/// Defaults to 1.0, which means each page fills the viewport in the scrolling
/// direction.
final double viewportFraction;
/// The current page displayed in the controlled [PreloadPageView].
///
/// There are circumstances that this [PreloadPageController] can't know the current
/// page. Reading [page] will throw an [AssertionError] in the following cases:
///
/// 1. No [PreloadPageView] is currently using this [PreloadPageController]. Once a
/// [PreloadPageView] starts using this [PreloadPageController], the new [page]
/// position will be derived:
///
/// * First, based on the attached [PreloadPageView]'s [BuildContext] and the
/// position saved at that context's [PageStorage] if [keepPage] is true.
/// * Second, from the [PreloadPageController]'s [initialPage].
///
/// 2. More than one [PreloadPageView] using the same [PreloadPageController].
///
/// The [hasClients] property can be used to check if a [PreloadPageView] is attached
/// prior to accessing [page].
double? get page {
assert(
positions.isNotEmpty,
'PageController.page cannot be accessed before a PageView is built with it.',
);
assert(
positions.length == 1,
'The page property cannot be read when multiple PageViews are attached to '
'the same PageController.',
);
final _PagePosition position = this.position as _PagePosition;
return position.page;
}
/// Animates the controlled [PreloadPageView] from the current page to the given page.
///
/// The animation lasts for the given duration and follows the given curve.
/// The returned [Future] resolves when the animation completes.
///
/// The `duration` and `curve` arguments must not be null.
Future<void> animateToPage(
int page, {
required Duration duration,
required Curve curve,
}) {
final _PagePosition position = this.position as _PagePosition;
return position.animateTo(
position.getPixelsFromPage(page.toDouble()),
duration: duration,
curve: curve,
);
}
/// Changes which page is displayed in the controlled [PreloadPageView].
///
/// Jumps the page position from its current value to the given value,
/// without animation, and without checking if the new value is in range.
void jumpToPage(int page) {
final _PagePosition position = this.position as _PagePosition;
position.jumpTo(position.getPixelsFromPage(page.toDouble()));
}
/// Animates the controlled [PreloadPageView] to the next page.
///
/// The animation lasts for the given duration and follows the given curve.
/// The returned [Future] resolves when the animation completes.
///
/// The `duration` and `curve` arguments must not be null.
Future<void> nextPage({required Duration duration, required Curve curve}) {
return animateToPage(page!.round() + 1, duration: duration, curve: curve);
}
/// Animates the controlled [PreloadPageView] to the previous page.
///
/// The animation lasts for the given duration and follows the given curve.
/// The returned [Future] resolves when the animation completes.
///
/// The `duration` and `curve` arguments must not be null.
Future<void> previousPage(
{required Duration duration, required Curve curve}) {
return animateToPage(page!.round() - 1, duration: duration, curve: curve);
}
@override
ScrollPosition createScrollPosition(ScrollPhysics physics,
ScrollContext context, ScrollPosition? oldPosition) {
return _PagePosition(
physics: physics,
context: context,
initialPage: initialPage,
keepPage: keepPage,
viewportFraction: viewportFraction,
oldPosition: oldPosition,
);
}
@override
void attach(ScrollPosition position) {
super.attach(position);
final _PagePosition pagePosition = position as _PagePosition;
pagePosition.viewportFraction = viewportFraction;
}
}
/// Metrics for a [PreloadPageView].
///
/// The metrics are available on [ScrollNotification]s generated from
/// [PreloadPageView]s.
class PageMetrics extends FixedScrollMetrics {
/// Creates an immutable snapshot of values associated with a [PreloadPageView].
PageMetrics({
required double? minScrollExtent,
required double? maxScrollExtent,
required double? pixels,
required double? viewportDimension,
required double devicePixelRatio,
required AxisDirection axisDirection,
required this.viewportFraction,
}) : super(
minScrollExtent: minScrollExtent,
maxScrollExtent: maxScrollExtent,
pixels: pixels,
viewportDimension: viewportDimension,
axisDirection: axisDirection,
devicePixelRatio: devicePixelRatio,
);
@override
PageMetrics copyWith({
double? minScrollExtent,
double? maxScrollExtent,
double? pixels,
double? viewportDimension,
AxisDirection? axisDirection,
double? viewportFraction,
double? devicePixelRatio,
}) {
return PageMetrics(
minScrollExtent: minScrollExtent ?? this.minScrollExtent,
maxScrollExtent: maxScrollExtent ?? this.maxScrollExtent,
pixels: pixels ?? this.pixels,
viewportDimension: viewportDimension ?? this.viewportDimension,
axisDirection: axisDirection ?? this.axisDirection,
viewportFraction: viewportFraction ?? this.viewportFraction,
devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio,
);
}
/// The current page displayed in the [PreloadPageView].
double? get page {
return math.max(0.0, pixels.clamp(minScrollExtent, maxScrollExtent)) /
math.max(1.0, viewportDimension * viewportFraction);
}
/// The fraction of the viewport that each page occupies.
///
/// Used to compute [page] from the current [pixels].
final double viewportFraction;
}
class _PagePosition extends ScrollPositionWithSingleContext
implements PageMetrics {
_PagePosition({
required ScrollPhysics physics,
required ScrollContext context,
this.initialPage = 0,
bool keepPage = true,
double viewportFraction = 1.0,
ScrollPosition? oldPosition,
}) : assert(viewportFraction > 0.0),
_viewportFraction = viewportFraction,
_pageToUseOnStartup = initialPage.toDouble(),
super(
physics: physics,
context: context,
initialPixels: null,
keepScrollOffset: keepPage,
oldPosition: oldPosition,
);
final int initialPage;
double _pageToUseOnStartup;
@override
double get viewportFraction => _viewportFraction;
double _viewportFraction;
set viewportFraction(double value) {
if (_viewportFraction == value) return;
final double? oldPage = page;
_viewportFraction = value;
if (oldPage != null) forcePixels(getPixelsFromPage(oldPage));
}
double? getPageFromPixels(double? pixels, double? viewportDimension) {
if (pixels == null || viewportDimension == null) {
return null;
}
return math.max(0.0, pixels) /
math.max(1.0, viewportDimension * viewportFraction);
}
double getPixelsFromPage(double page) {
return page *
(hasViewportDimension ? viewportDimension : 0) *
viewportFraction;
}
@override
double? get page => hasPixels
? getPageFromPixels(
hasContentDimensions
? pixels.clamp(minScrollExtent, maxScrollExtent)
: null,
hasViewportDimension ? viewportDimension : null,
)
: null;
@override
void saveScrollOffset() {
PageStorage.of(context.storageContext).writeState(
context.storageContext,
getPageFromPixels(hasPixels ? pixels : null,
hasViewportDimension ? viewportDimension : null));
}
@override
void restoreScrollOffset() {
if (hasPixels == true) {
final double? value = PageStorage.of(context.storageContext)
.readState(context.storageContext);
if (value != null) _pageToUseOnStartup = value;
}
}
@override
bool applyViewportDimension(double viewportDimension) {
final double? oldViewportDimensions =
(hasViewportDimension) ? this.viewportDimension : null;
final bool result = super.applyViewportDimension(viewportDimension);
final double? oldPixels = (hasPixels) ? pixels : null;
final double? page = (oldPixels == null || oldViewportDimensions == 0.0)
? _pageToUseOnStartup
: getPageFromPixels(oldPixels, oldViewportDimensions!);
final double? newPixels = page != null ? getPixelsFromPage(page) : null;
if (newPixels != null && newPixels != oldPixels) {
correctPixels(newPixels);
return false;
}
return result;
}
@override
PageMetrics copyWith({
double? minScrollExtent,
double? maxScrollExtent,
double? pixels,
double? viewportDimension,
AxisDirection? axisDirection,
double? viewportFraction,
double? devicePixelRatio,
}) {
return PageMetrics(
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,
viewportFraction: viewportFraction ?? this.viewportFraction,
devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio,
);
}
}
/// Scroll physics used by a [PreloadPageView].
///
/// These physics cause the page view to snap to page boundaries.
///
/// See also:
///
/// * [ScrollPhysics], the base class which defines the API for scrolling
/// physics.
/// * [PreloadPageView.physics], which can override the physics used by a page view.
class PageScrollPhysics extends ScrollPhysics {
/// Creates physics for a [PreloadPageView].
const PageScrollPhysics({ScrollPhysics? parent}) : super(parent: parent);
@override
PageScrollPhysics applyTo(ScrollPhysics? ancestor) {
return PageScrollPhysics(parent: buildParent(ancestor));
}
double _getPage(ScrollPosition position) {
if (position is _PagePosition && position.page != null) {
return position.page!;
}
return position.pixels / position.viewportDimension;
}
double _getPixels(ScrollPosition position, double page) {
if (position is _PagePosition) return position.getPixelsFromPage(page);
return page * position.viewportDimension;
}
double _getTargetPixels(
ScrollPosition position, Tolerance tolerance, double velocity) {
double? page = _getPage(position);
if (velocity < -tolerance.velocity) {