-
-
Notifications
You must be signed in to change notification settings - Fork 641
/
indicator_notifier.dart
1265 lines (1144 loc) · 36.9 KB
/
indicator_notifier.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: invalid_use_of_visible_for_testing_member
part of '../../easy_refresh.dart';
/// Indicator widget builder.
typedef CanProcessCallBack = bool Function();
/// Mode change listener.
typedef ModeChangeListener = void Function(IndicatorMode mode, double offset);
/// Indicator data and trigger notification.
abstract class IndicatorNotifier extends ChangeNotifier {
/// Refresh and loading Indicator.
Indicator _indicator;
/// Used to provide [clamping] animation.
final TickerProviderStateMixin vsync;
/// User triggered notifier.
/// Record user triggers and releases.
@protected
final ValueNotifier<bool> userOffsetNotifier;
/// Tasks that need to be executed when triggered.
/// Can return [IndicatorResult] to set the completion result.
FutureOr Function()? _task;
/// Wait for the task to complete.
bool _waitTaskResult;
/// Mounted on EasyRefresh.
bool _mounted = false;
/// Direction of execution.
/// Other scroll directions will not show indicators and perform task.
Axis? _triggerAxis;
IndicatorNotifier({
required Indicator indicator,
required this.vsync,
required this.userOffsetNotifier,
required CanProcessCallBack onCanProcess,
required bool canProcessAfterNoMore,
required bool isNested,
Axis? triggerAxis,
bool waitTaskResult = true,
FutureOr Function()? task,
}) : _indicator = indicator,
_onCanProcess = onCanProcess,
_canProcessAfterNoMore = canProcessAfterNoMore,
_isNested = isNested,
_triggerAxis = triggerAxis,
_waitTaskResult = waitTaskResult,
_task = task {
_initClampingAnimation();
userOffsetNotifier.addListener(_onUserOffset);
indicator.listenable?._bind(this);
_mounted = true;
}
double get triggerOffset => _indicator.triggerOffset;
bool get clamping => _indicator.clamping;
bool get safeArea => _indicator.safeArea;
Duration get processedDuration => _indicator.processedDuration;
double? get infiniteOffset => _indicator.infiniteOffset;
bool get hitOver => _indicator.hitOver;
bool get infiniteHitOver => _indicator.infiniteHitOver;
IndicatorPosition get iPosition => _indicator.position;
double? get secondaryTriggerOffset => _indicator.secondaryTriggerOffset;
double get secondaryVelocity => _indicator.secondaryVelocity;
double get maxOverOffset => _indicator.maxOverOffset;
double get actualMaxOverOffset => maxOverOffset == double.infinity
? maxOverOffset
: (maxOverOffset + safeOffset);
/// Spring description.
physics.SpringDescription? get _spring {
if (_axis == Axis.horizontal) {
return _indicator.horizontalSpring ?? _indicator.spring;
} else {
return _indicator.spring;
}
}
physics.SpringDescription get spring => _physics.spring;
SpringBuilder? get readySpringBuilder {
if (_axis == Axis.horizontal) {
return _indicator.horizontalReadySpringBuilder ??
_indicator.readySpringBuilder;
} else {
return _indicator.readySpringBuilder;
}
}
FrictionFactor? get _frictionFactor {
if (_axis == Axis.horizontal) {
return _indicator.horizontalFrictionFactor ?? _indicator.frictionFactor;
} else {
return _indicator.frictionFactor;
}
}
FrictionFactor get frictionFactor => _physics.frictionFactor;
double get secondaryDimension =>
_indicator.secondaryDimension ?? viewportDimension;
double get secondaryCloseTriggerOffset =>
_indicator.secondaryCloseTriggerOffset;
bool get hapticFeedback => _indicator.hapticFeedback;
bool get hasSecondary => secondaryTriggerOffset != null;
/// [Scrollable] axis and direction
Axis? _axis;
Axis? get axis => _axis;
AxisDirection? _axisDirection;
AxisDirection? get axisDirection => _axisDirection;
/// Safe area offset.
/// Refer to [SafeArea].
/// Used to solve the problem that the safe area is blocked.
/// The final trigger offset is [triggerOffset] + [safeOffset]
double? _safeOffset;
double get safeOffset => safeArea ? _safeOffset ?? 0 : 0;
/// Overscroll offset.
double _offset = 0;
double get offset => _offset;
/// The current scroll position.
ScrollMetrics get position => _position!;
/// Handling NestedScrollView
bool _isNested;
bool get isNested => _isNested;
set position(ScrollMetrics value) {
if (_isNested) {
if (value.isNestedOuter) {
_viewportDimension = value.viewportDimension;
} else if (value.isNestedInner) {
if (WidgetsBinding.instance.schedulerPhase !=
SchedulerPhase.persistentCallbacks) {
_viewportDimension = value.axis == Axis.vertical
? vsync.context.size?.height
: vsync.context.size?.width;
}
}
} else {
_viewportDimension = null;
}
_position = value;
_lastMaxScrollExtent = value.maxScrollExtent;
}
ScrollMetrics? _position;
/// Cache maxScrollExtent.
/// Used to compare the last value.
double? _lastMaxScrollExtent;
/// The current scroll velocity.
double _velocity = 0;
double get velocity => _velocity;
/// The current state of the indicator.
IndicatorMode __mode = IndicatorMode.inactive;
IndicatorMode get _mode => __mode;
set _mode(IndicatorMode mode) {
final oldMode = __mode;
__mode = mode;
if (mode != oldMode) {
for (final listener in _modeChangeListeners) {
listener(mode, _offset);
}
}
}
IndicatorMode get mode => _mode;
/// Animation controller.
/// Used when [clamping] is true.
AnimationController? _clampingAnimationController;
/// EasyRefresh scroll physics.
late _ERScrollPhysics _physics;
/// Offset on release.
/// Meet the premise of the task.
double _releaseOffset = 0;
/// Mode change listeners.
final Set<ModeChangeListener> _modeChangeListeners = {};
/// Actual trigger offset.
/// [triggerOffset] + [safeOffset]
double get actualTriggerOffset => triggerOffset + safeOffset;
/// Actual secondary trigger offset.
/// [secondaryTriggerOffset] + [safeOffset]
double get actualSecondaryTriggerOffset =>
secondaryTriggerOffset! + safeOffset;
/// Whether to support the direction.
bool get _isSupportAxis {
if (_triggerAxis == null || _axis == null) {
return true;
}
return _axis == _triggerAxis;
}
/// Keep the extent of the [Scrollable] out of bounds.
double get overExtent {
// If the direction is different do not change.
if (!_isSupportAxis) {
return 0;
}
// State that doesn't change.
if (_task == null ||
(!_canProcess && !noMoreLocked) ||
(noMoreLocked && infiniteOffset == null)) {
return 0;
}
// State that triggers the task.
if (infiniteOffset != null ||
_mode == IndicatorMode.ready ||
modeLocked ||
noMoreLocked) {
return actualTriggerOffset;
}
// State that triggers the secondary.
if (_mode == IndicatorMode.secondaryArmed && userOffsetNotifier.value) {
return offset;
}
if (_mode == IndicatorMode.secondaryReady ||
_mode == IndicatorMode.secondaryOpen) {
return secondaryDimension;
}
return 0;
}
/// Is the state locked.
bool get modeLocked =>
_mode == IndicatorMode.processing || _mode == IndicatorMode.processed;
/// Out of scroll area.
bool get outOfRange {
if (clamping) {
return !modeLocked && _offset > 0;
}
return _offset > 0;
}
/// Indicator listenable.
ValueListenable<IndicatorNotifier> listenable() => _IndicatorListenable(this);
/// Is the task in progress.
bool _processing = false;
/// Can it be process.
CanProcessCallBack? _onCanProcess;
bool get _canProcess => _onCanProcess?.call() ?? false;
/// Task completion result.
IndicatorResult _result = IndicatorResult.none;
/// Whether to execute the task after no more.
bool _canProcessAfterNoMore;
/// State lock when no more.
bool get noMoreLocked =>
!_canProcessAfterNoMore &&
_result == IndicatorResult.noMore &&
_mode == IndicatorMode.inactive;
/// [Scrollable] viewport dimension.
double get viewportDimension =>
_viewportDimension ?? position.viewportDimension;
double? _viewportDimension;
/// Calculate the overscroll offset.
double _calculateOffset(ScrollMetrics position, double value);
/// Calculate the overscroll offset with pixels.
double calculateOffsetWithPixels(ScrollMetrics position, double pixels);
/// Infinite scroll exclusions.
bool _infiniteExclude(ScrollMetrics position, double value);
/// Animates the position from its current value to the given value.
/// [offset] The offset to scroll to.
/// [mode] When duration is null and clamping is true, set the state.
/// [jumpToEdge] Whether to jump to the edge before scrolling.
/// [duration] See [ScrollPosition.animateTo].
/// [curve] See [ScrollPosition.animateTo].
/// [scrollController] When position is not [ScrollPosition], you can use [ScrollController].
Future animateToOffset({
required double offset,
required IndicatorMode mode,
bool jumpToEdge = true,
Duration? duration,
Curve curve = Curves.linear,
ScrollController? scrollController,
});
bool get secondaryLocked =>
_mode == IndicatorMode.secondaryOpen ||
_mode == IndicatorMode.secondaryClosing;
@override
void dispose() {
_onCanProcess = null;
_clampingAnimationController?.dispose();
userOffsetNotifier.removeListener(_onUserOffset);
_task = null;
_modeChangeListeners.clear();
_indicator.listenable?._unbind();
_mounted = false;
super.dispose();
}
/// Add mode change listener.
void addModeChangeListener(ModeChangeListener listener) {
_modeChangeListeners.add(listener);
}
/// Remove mode change listener.
void removeModeChangeListener(ModeChangeListener listener) {
_modeChangeListeners.remove(listener);
}
/// Initialize the [clamping] animation controller
void _initClampingAnimation() {
if (clamping) {
_clampingAnimationController = AnimationController.unbounded(
vsync: vsync,
);
_clampingAnimationController!.addListener(_clampingTick);
}
}
/// Listen for user events
void _onUserOffset() {
if (userOffsetNotifier.value) {
// Clamping
// Cancel animation, update offset
if (clamping && _clampingAnimationController!.isAnimating) {
_clampingAnimationController!.stop(canceled: true);
}
} else {
_releaseOffset = _offset;
}
}
/// Bind physics behavior
void _bindPhysics(_ERScrollPhysics physics) {
_physics = physics;
}
/// Create a ballistic simulation.
/// Use for [clamping].
Simulation? createBallisticSimulation(
ScrollMetrics position, double velocity);
/// Calculate distance from edge.
double get edgeOffset;
/// Update parameters.
/// When the EasyRefresh parameters is updated.
void _update({
Indicator? indicator,
bool? canProcessAfterNoMore,
Axis? triggerAxis,
FutureOr Function()? task,
bool? waitTaskRefresh,
bool? isNested,
}) {
if (indicator != null) {
if (indicator.listenable == _indicator.listenable) {
indicator.listenable?._rebind(this);
} else {
_indicator.listenable?._unbind();
indicator.listenable?._bind(this);
}
if (indicator != _indicator) {
_indicator = indicator;
}
}
_canProcessAfterNoMore = canProcessAfterNoMore ?? _canProcessAfterNoMore;
_triggerAxis = triggerAxis;
_task = task;
_waitTaskResult = waitTaskRefresh ?? _waitTaskResult;
if (_indicator.clamping && _clampingAnimationController == null) {
_initClampingAnimation();
} else if (!_indicator.clamping && _clampingAnimationController != null) {
_clampingAnimationController?.stop();
_clampingAnimationController?.dispose();
_clampingAnimationController = null;
}
if (isNested != null) {
_isNested = isNested;
}
notifyListeners();
}
/// Reset partial state, e.g. no more.
void _reset() {
if (_result == IndicatorResult.noMore) {
_result = IndicatorResult.none;
}
}
/// Automatically trigger task.
/// [overOffset] Offset beyond the trigger offset, must be greater than 0.
/// [duration] See [ScrollPosition.animateTo].
/// [curve] See [ScrollPosition.animateTo].
/// [scrollController] When position is not [ScrollPosition], you can use [ScrollController].
/// [force] Enforce execution even if the task is in progress. But you have to handle the completion event.
Future callTask({
required double overOffset,
Duration? duration,
Curve curve = Curves.linear,
ScrollController? scrollController,
bool force = false,
}) {
if (!_mounted) {
return Future.value();
}
if (!force) {
if (modeLocked || noMoreLocked || secondaryLocked || !_canProcess) {
return Future.value();
}
} else {
_offset = 0;
_mode = IndicatorMode.inactive;
_processing = false;
}
return animateToOffset(
offset: actualTriggerOffset + overOffset,
mode: IndicatorMode.ready,
duration: duration,
curve: curve,
scrollController: scrollController,
);
}
/// Animation listener for [clamping].
void _clampingTick() {
final mOffset = calculateOffsetWithPixels(
position, _clampingAnimationController!.value);
if (hasSecondary &&
!noMoreLocked &&
mOffset > secondaryDimension &&
_mode == IndicatorMode.secondaryReady) {
// After fully opening the secondary, turn off the animation.
_offset = secondaryDimension;
_clampingAnimationController!.stop();
} else {
// Stop spring rebound.
if (_mode == IndicatorMode.ready &&
!_indicator.springRebound &&
mOffset < actualTriggerOffset) {
_offset = actualTriggerOffset;
_clampingAnimationController!.stop();
} else {
if (mOffset < 0) {
_offset = 0;
_clampingAnimationController!.stop();
}
_offset = mOffset;
}
}
_slightDeviation();
_updateMode();
notifyListeners();
}
/// Update by [ScrollPhysics.createBallisticSimulation].
void _updateBySimulation(ScrollMetrics position, double velocity) {
_velocity = velocity;
// Update axis and direction.
if (_axis != position.axis || _axisDirection != position.axisDirection) {
_axis = position.axis;
_axisDirection = position.axisDirection;
Future(() {
if (_mounted) {
notifyListeners();
}
});
}
this.position = position;
final oldMode = _mode;
// Update offset on release
_updateOffset(position, position.pixels, true);
// If clamping is true and offset is greater than 0, start animation
if (clamping &&
_offset > 0 &&
((_indicator.triggerWhenRelease && oldMode == IndicatorMode.armed) ||
!(modeLocked || secondaryLocked))) {
final simulation = createBallisticSimulation(position, velocity);
if (simulation != null) {
_startClampingAnimation(simulation);
}
}
}
/// Temporary solutions, sometimes with slight deviation.
void _slightDeviation() {
if ((_offset - actualTriggerOffset).abs() <= precisionErrorTolerance) {
_offset = actualTriggerOffset;
}
}
/// Update [Scrollable] offset
void _updateOffset(ScrollMetrics position, double value, bool bySimulation) {
// Clamping
// In task processing, do nothing.
if (clamping && (modeLocked || secondaryLocked)) {
return;
}
// Clamping
// In the case of release, and offset is greater than 0, it is controlled by animation.
if ((_mode == IndicatorMode.done && bySimulation) ||
!userOffsetNotifier.value && clamping && _offset > 0 && !bySimulation) {
return;
}
this.position = position;
// Record old state.
final oldOffset = _offset;
final oldMode = _mode;
// Calculate and update the offset.
_offset = _calculateOffset(position, value);
_slightDeviation();
// Do nothing if not out of bounds.
if (oldOffset == 0 && _offset == 0) {
if (_mode == IndicatorMode.done ||
// Handling infinite scroll
(infiniteOffset != null &&
(!(_isNested && position.isNestedOuter) &&
edgeOffset < infiniteOffset!) &&
!bySimulation &&
!_infiniteExclude(position, value))) {
// Update mode
_updateMode(oldOffset);
notifyListeners();
}
if (_indicator.notifyWhenInvisible && !bySimulation) {
notifyListeners();
}
return;
}
// Update mode
_updateMode(oldOffset);
// Need notify
if (oldOffset == _offset && oldMode == _mode) {
return;
}
// Haptic feedback
if (hapticFeedback && userOffsetNotifier.value) {
if (_indicator.triggerWhenReach) {
if (_mode == IndicatorMode.processing &&
oldMode == IndicatorMode.drag) {
HapticFeedback.mediumImpact();
}
} else {
if (_mode == IndicatorMode.armed && oldMode != IndicatorMode.armed) {
HapticFeedback.mediumImpact();
}
}
}
// Avoid setState() during drawing
if (bySimulation) {
// Notify when list length changes
if (_offset <= actualTriggerOffset) {
Future(() {
if (_mounted) {
notifyListeners();
}
});
}
return;
}
notifyListeners();
}
/// Update indicator state.
void _updateMode([double? oldOffset]) {
// When the orientation is different, no modification is made.
if (!_isSupportAxis) {
return;
}
// No task, keep IndicatorMode.inactive state.
if (_task == null) {
if (_mode != IndicatorMode.inactive) {
_mode = IndicatorMode.inactive;
}
return;
}
// Not updated during task execution and task completion.
if (!(modeLocked || noMoreLocked || secondaryLocked)) {
// In the non-executable task state.
if (!_canProcess) {
_mode = IndicatorMode.inactive;
return;
}
// Infinite scroll
if (infiniteOffset != null &&
(!(_isNested && position.isNestedOuter) &&
edgeOffset < infiniteOffset!)) {
if (_mode == IndicatorMode.done &&
position.maxScrollExtent != position.minScrollExtent) {
if ((_result == IndicatorResult.fail ||
(_result == IndicatorResult.noMore &&
_canProcessAfterNoMore)) &&
oldOffset != null &&
oldOffset < _offset) {
// Trigger task if in failed state.
_result = IndicatorResult.none;
_mode = IndicatorMode.processing;
} else {
// The state does not change until the end
return;
}
} else {
if (_mode == IndicatorMode.done) {
if (offset == 0) {
_mode = IndicatorMode.inactive;
}
} else {
_result = IndicatorResult.none;
_mode = IndicatorMode.processing;
}
}
} else if (_mode == IndicatorMode.done && offset > 0) {
// The state does not change until the end
return;
} else if (_offset == 0) {
if (!(_mode == IndicatorMode.ready && !userOffsetNotifier.value)) {
// Prevent Spring from having repeated rebounds.
_mode = IndicatorMode.inactive;
if (_result != IndicatorResult.noMore || _canProcessAfterNoMore) {
_result = IndicatorResult.none;
}
_releaseOffset = 0;
}
} else if (_offset < actualTriggerOffset) {
if (_canProcessAfterNoMore &&
_result == IndicatorResult.noMore &&
userOffsetNotifier.value) {
_result = IndicatorResult.none;
}
if (!(_mode == IndicatorMode.ready && !userOffsetNotifier.value)) {
// Prevent Spring from having repeated rebounds.
_mode = IndicatorMode.drag;
}
} else if (_offset == actualTriggerOffset) {
// Must be exceeded to trigger the task
if (userOffsetNotifier.value) {
if (_indicator.triggerWhenReach) {
_mode = IndicatorMode.processing;
} else {
_mode = (_releaseOffset > actualTriggerOffset
? IndicatorMode.ready
: IndicatorMode.armed);
}
} else {
_mode = IndicatorMode.processing;
}
} else if (_offset > actualTriggerOffset) {
if (hasSecondary &&
_offset >= actualSecondaryTriggerOffset &&
(_releaseOffset == 0 ||
_releaseOffset >= actualSecondaryTriggerOffset)) {
// Secondary
if (_offset < secondaryDimension) {
_mode = userOffsetNotifier.value
? IndicatorMode.secondaryArmed
: IndicatorMode.secondaryReady;
} else {
_mode = userOffsetNotifier.value
? IndicatorMode.secondaryReady
: IndicatorMode.secondaryOpen;
}
} else {
// Process
// If the user is scrolling
// (the task is not executed if it is not released)
if (userOffsetNotifier.value) {
_mode = _indicator.triggerWhenReach
? IndicatorMode.processing
: IndicatorMode.armed;
} else {
if (_releaseOffset > actualTriggerOffset) {
if (_indicator.triggerWhenReleaseNoWait) {
// Immediately trigger the task.
// No need to wait for events to complete.
// Mode changes to IndicatorMode.done.
if (_task != null) {
Future.sync(_task!);
}
_mode = IndicatorMode.done;
} else if (_indicator.triggerWhenRelease) {
// Immediately trigger the task.
_mode = IndicatorMode.processing;
} else {
_mode = IndicatorMode.ready;
}
} else {
_mode = IndicatorMode.armed;
}
}
}
}
// Execute the task.
if (_mode == IndicatorMode.processing) {
_onTask();
}
}
// Close secondary
if (secondaryLocked) {
_mode = secondaryDimension - _offset >= secondaryCloseTriggerOffset
? IndicatorMode.secondaryClosing
: IndicatorMode.secondaryOpen;
if (_offset == 0) {
_mode = IndicatorMode.inactive;
}
}
}
/// Execute the task and process the result.
void _onTask() async {
if (!(_canProcess && !_processing && _task != null)) {
return;
}
_processing = true;
if (_waitTaskResult) {
try {
final res = await Future.sync(_task!);
if (res is IndicatorResult) {
_result = res;
} else {
_result = IndicatorResult.success;
}
} catch (_) {
_result = IndicatorResult.fail;
rethrow;
} finally {
_setMode(IndicatorMode.processed);
_processing = false;
}
} else {
Future.sync(_task!);
}
}
/// Finish task and return the result.
/// [result] Result of task completion.
void _finishTask([IndicatorResult result = IndicatorResult.success]) {
_result = result;
if (!_waitTaskResult && mode == IndicatorMode.processing) {
_setMode(IndicatorMode.processed);
_processing = false;
}
}
/// Start [clamping] animation
void _startClampingAnimation(Simulation simulation) {
if (_offset <= 0 || _clampingAnimationController!.isAnimating) {
return;
}
_clampingAnimationController!.animateWith(simulation);
}
/// Reset ballistic.
/// Trigger [_ERScrollPhysics.createBallisticSimulation].
void _resetBallistic() {
ScrollActivityDelegate? delegate;
double velocity = 0;
if (_position is ScrollPosition) {
// ignore: invalid_use_of_protected_member
final activity = (_position as ScrollPosition).activity;
delegate = activity?.delegate;
velocity = activity?.velocity ?? 0;
} else if (_position is ScrollActivityDelegate) {
delegate = _position as ScrollActivityDelegate;
}
if (delegate != null) {
delegate.goBallistic(velocity);
} else {
if (clamping && _offset > 0 && !(modeLocked || secondaryLocked)) {
final simulation = createBallisticSimulation(position, velocity);
if (simulation != null) {
_startClampingAnimation(simulation);
}
}
}
}
/// Set mode.
/// Internal use of EasyRefresh.
void _setMode(IndicatorMode mode) {
if (_mode == mode) {
return;
}
// Do not continue if not mounted.
if (!_mounted) {
return;
}
final oldMode = _mode;
_mode = mode;
notifyListeners();
// Task processed
if (this.mode == IndicatorMode.processed) {
// Completion delay
if (processedDuration == Duration.zero) {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
if (this.mode == IndicatorMode.processed) {
_mode = IndicatorMode.done;
if (offset == 0) {
_mode = IndicatorMode.inactive;
}
// Trigger [Scrollable] rollback
if (oldMode == IndicatorMode.processing &&
!userOffsetNotifier.value) {
_resetBallistic();
}
}
});
} else {
Future.delayed(processedDuration, () {
if (this.mode == IndicatorMode.processed) {
_setMode(IndicatorMode.done);
if (offset == 0) {
_setMode(IndicatorMode.inactive);
}
// Trigger [Scrollable] rollback
if (!userOffsetNotifier.value) {
_resetBallistic();
}
}
});
}
// Actively update the offset if the user does not release
if (!clamping && userOffsetNotifier.value) {
Future(() {
_updateOffset(position, position.pixels, false);
});
}
}
}
/// Get indicator state;
IndicatorState? get indicatorState {
if (_axis == null || _axisDirection == null) {
return null;
}
return IndicatorState(
indicator: _indicator,
userOffsetNotifier: userOffsetNotifier,
notifier: this,
mode: mode,
result: _result,
offset: offset,
safeOffset: safeOffset,
axis: _axis!,
axisDirection: _axisDirection!,
viewportDimension: viewportDimension,
actualTriggerOffset: actualTriggerOffset,
);
}
/// Build indicator widget.
Widget _build(BuildContext context) {
if (_axis == null || _axisDirection == null) {
return const SizedBox();
}
if (!_isSupportAxis) {
return const SizedBox();
}
return _indicator.build(
context,
indicatorState!,
);
}
}
/// Indicator listenable.
/// Listen for property changes of the indicator.
/// Used to update widget.
class _IndicatorListenable<T extends IndicatorNotifier>
extends ValueListenable<T> {
/// Indicator notifier
final T _indicatorNotifier;
_IndicatorListenable(this._indicatorNotifier);
final List<VoidCallback> _listeners = [];
/// Listen for notifications
void _onNotify() {
for (final listener in _listeners) {
listener();
}
}
@override
void addListener(VoidCallback listener) {
if (_listeners.isEmpty) {
_indicatorNotifier.addListener(_onNotify);
}
_listeners.add(listener);
}
@override
void removeListener(VoidCallback listener) {
_listeners.remove(listener);
if (_listeners.isEmpty) {
_indicatorNotifier.removeListener(_onNotify);
}
}
@override
T get value => _indicatorNotifier;
}
/// [Header] notifier
/// [Header] status and Notifications
class HeaderNotifier extends IndicatorNotifier {
HeaderNotifier({
required Header header,
required super.userOffsetNotifier,
required super.vsync,
required CanProcessCallBack onCanRefresh,
super.canProcessAfterNoMore = false,
super.isNested = false,
bool canProcessAfterFail = true,
super.triggerAxis,
FutureOr Function()? onRefresh,
bool waitRefreshResult = true,
}) : super(
indicator: header,
onCanProcess: onCanRefresh,
task: onRefresh,
waitTaskResult: waitRefreshResult,
);
@override
double _calculateOffset(ScrollMetrics position, double value) {
if (value >= position.minScrollExtent &&
_offset != 0 &&
!(clamping && _offset > 0)) {
return 0;
}
// Moving distance
final move = position.minScrollExtent - value;
if (clamping) {
if (value > position.minScrollExtent) {
// Rollback first minus offset.
return math.max(_offset > 0 ? (move + _offset) : 0, 0);
} else {
// Overscroll accumulated offset.
final mOffset = move + _offset;
if (hasSecondary && mOffset > secondaryDimension) {
// Cannot exceed secondary offset.
return secondaryDimension;
}
// Maximum overscroll offset
if (actualMaxOverOffset != double.infinity) {
return math.min(mOffset, actualMaxOverOffset);
}
return mOffset;
}
} else {
return value > position.minScrollExtent ? 0 : move;
}