Repository navigation
Expand file tree
/
Copy pathscrollbar.dart
More file actions
2530 lines (2308 loc) · 92 KB
/
Copy pathscrollbar.dart
File metadata and controls
2530 lines (2308 loc) · 92 KB
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
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// @docImport 'package:flutter/cupertino.dart';
/// @docImport 'package:flutter/material.dart';
/// @docImport 'package:flutter_test/flutter_test.dart';
///
/// @docImport 'editable_text.dart';
/// @docImport 'list_wheel_scroll_view.dart';
/// @docImport 'nested_scroll_view.dart';
/// @docImport 'page_view.dart';
/// @docImport 'scroll_view.dart';
/// @docImport 'widget_state.dart';
library;
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'basic.dart';
import 'binding.dart';
import 'framework.dart';
import 'gesture_detector.dart';
import 'media_query.dart';
import 'notification_listener.dart';
import 'primary_scroll_controller.dart';
import 'scroll_configuration.dart';
import 'scroll_controller.dart';
import 'scroll_metrics.dart';
import 'scroll_notification.dart';
import 'scroll_position.dart';
import 'scrollable.dart';
import 'scrollable_helpers.dart';
import 'ticker_provider.dart';
import 'widget_state.dart';
const double _kMinThumbExtent = 18.0;
const double _kMinInteractiveSize = 48.0;
const double _kScrollbarThickness = 6.0;
const Duration _kScrollbarFadeDuration = Duration(milliseconds: 300);
const Duration _kScrollbarTimeToFade = Duration(milliseconds: 600);
/// An orientation along either the horizontal or vertical [Axis].
enum ScrollbarOrientation {
/// Place towards the left of the screen.
left,
/// Place towards the right of the screen.
right,
/// Place on top of the screen.
top,
/// Place on the bottom of the screen.
bottom,
}
/// Paints a scrollbar's track and thumb.
///
/// The size of the scrollbar along its scroll direction is typically
/// proportional to the percentage of content completely visible on screen,
/// as long as its size isn't less than [minLength] and it isn't overscrolling.
///
/// If [padding] is an [EdgeInsetsDirectional], a non-null [textDirection] must
/// be provided to properly resolve the padding values.
///
/// Unlike [CustomPainter]s that subclasses [CustomPainter] and only repaint
/// when [shouldRepaint] returns true (which requires this [CustomPainter] to
/// be rebuilt), this painter has the added optimization of repainting and not
/// rebuilding when:
///
/// * the scroll position changes; and
/// * when the scrollbar fades away.
///
/// Calling [update] with the new [ScrollMetrics] will repaint the new scrollbar
/// position.
///
/// Updating the value on the provided [fadeoutOpacityAnimation] will repaint
/// with the new opacity.
///
/// You must call [dispose] on this [ScrollbarPainter] when it's no longer used.
///
/// See also:
///
/// * [Scrollbar] for a widget showing a scrollbar around a [Scrollable] in the
/// Material Design style.
/// * [CupertinoScrollbar] for a widget showing a scrollbar around a
/// [Scrollable] in the iOS style.
class ScrollbarPainter extends ChangeNotifier implements CustomPainter {
/// Creates a scrollbar with customizations given by construction arguments.
ScrollbarPainter({
required this._color,
required this.fadeoutOpacityAnimation,
this._trackColor = const Color(0x00000000),
this._trackBorderColor = const Color(0x00000000),
TextDirection? textDirection,
this._thickness = _kScrollbarThickness,
EdgeInsetsGeometry padding = EdgeInsets.zero,
this._mainAxisMargin = 0.0,
this._crossAxisMargin = 0.0,
Radius? radius,
this._trackRadius,
OutlinedBorder? shape,
double minLength = _kMinThumbExtent,
double? minOverscrollLength,
this._scrollbarOrientation,
this._ignorePointer = false,
}) : assert(radius == null || shape == null),
assert(minLength >= 0),
assert(minOverscrollLength == null || minOverscrollLength <= minLength),
assert(minOverscrollLength == null || minOverscrollLength >= 0),
assert(padding.isNonNegative),
assert(
padding is! EdgeInsetsDirectional || textDirection != null,
'A non-null textDirection must be provided when using EdgeInsetsDirectional for padding.',
),
_textDirection = textDirection,
_radius = radius,
_shape = shape,
_padding = padding,
_resolvedPadding = padding.resolve(textDirection),
_minLength = minLength,
_minOverscrollLength = minOverscrollLength ?? minLength {
fadeoutOpacityAnimation.addListener(notifyListeners);
}
/// [Color] of the thumb. Mustn't be null.
Color get color => _color;
Color _color;
set color(Color value) {
if (color == value) {
return;
}
_color = value;
notifyListeners();
}
/// [Color] of the track. Mustn't be null.
Color get trackColor => _trackColor;
Color _trackColor;
set trackColor(Color value) {
if (trackColor == value) {
return;
}
_trackColor = value;
notifyListeners();
}
/// [Color] of the track border. Mustn't be null.
Color get trackBorderColor => _trackBorderColor;
Color _trackBorderColor;
set trackBorderColor(Color value) {
if (trackBorderColor == value) {
return;
}
_trackBorderColor = value;
notifyListeners();
}
/// [Radius] of corners of the Scrollbar's track.
///
/// Scrollbar's track will be rectangular if [trackRadius] is null.
Radius? get trackRadius => _trackRadius;
Radius? _trackRadius;
set trackRadius(Radius? value) {
if (trackRadius == value) {
return;
}
_trackRadius = value;
notifyListeners();
}
/// [TextDirection] of the [BuildContext] which dictates the side of the
/// screen the scrollbar appears in (the trailing side). Must be set prior to
/// calling paint.
TextDirection? get textDirection => _textDirection;
TextDirection? _textDirection;
set textDirection(TextDirection? value) {
assert(value != null);
if (textDirection == value) {
return;
}
_textDirection = value;
_resolvedPadding = _padding.resolve(_textDirection);
notifyListeners();
}
/// Thickness of the scrollbar in its cross-axis in logical pixels. Mustn't be null.
double get thickness => _thickness;
double _thickness;
set thickness(double value) {
if (thickness == value) {
return;
}
_thickness = value;
notifyListeners();
}
/// An opacity [Animation] that dictates the opacity of the thumb.
/// Changes in value of this [Listenable] will automatically trigger repaints.
/// Mustn't be null.
final Animation<double> fadeoutOpacityAnimation;
/// Distance from the scrollbar thumb's start and end to the edge of the
/// viewport in logical pixels. It affects the amount of available paint area.
///
/// The scrollbar track consumes this space.
///
/// Mustn't be null and defaults to 0.
double get mainAxisMargin => _mainAxisMargin;
double _mainAxisMargin;
set mainAxisMargin(double value) {
if (mainAxisMargin == value) {
return;
}
_mainAxisMargin = value;
notifyListeners();
}
/// Distance from the scrollbar thumb to the nearest cross axis edge
/// in logical pixels.
///
/// The scrollbar track consumes this space.
///
/// Defaults to zero.
double get crossAxisMargin => _crossAxisMargin;
double _crossAxisMargin;
set crossAxisMargin(double value) {
if (crossAxisMargin == value) {
return;
}
_crossAxisMargin = value;
notifyListeners();
}
/// [Radius] of corners if the scrollbar should have rounded corners.
///
/// Scrollbar will be rectangular if [radius] is null.
Radius? get radius => _radius;
Radius? _radius;
set radius(Radius? value) {
assert(shape == null || value == null);
if (radius == value) {
return;
}
_radius = value;
notifyListeners();
}
/// The [OutlinedBorder] of the scrollbar's thumb.
///
/// Only one of [radius] and [shape] may be specified. For a rounded rectangle,
/// it's simplest to just specify [radius]. By default, the scrollbar thumb's
/// shape is a simple rectangle.
///
/// If [shape] is specified, the thumb will take the shape of the passed
/// [OutlinedBorder] and fill itself with [color] (or grey if it
/// is unspecified).
///
OutlinedBorder? get shape => _shape;
OutlinedBorder? _shape;
set shape(OutlinedBorder? value) {
assert(radius == null || value == null);
if (shape == value) {
return;
}
_shape = value;
notifyListeners();
}
/// The amount of space by which to inset the scrollbar's start and end, as
/// well as its side to the nearest edge, in logical pixels.
///
/// This is typically set to the current [MediaQueryData.padding] to avoid
/// partial obstructions such as display notches. If you only want additional
/// margins around the scrollbar, see [mainAxisMargin].
///
/// Defaults to [EdgeInsets.zero]. Offsets from all four directions must be
/// greater than or equal to zero.
///
/// For RTL (right-to-left) support, you can provide [EdgeInsetsDirectional],
/// but you must also provide a non-null [textDirection] to properly resolve
/// the padding values. The scrollbar will automatically adjust the padding
/// based on the text direction.
EdgeInsetsGeometry get padding => _padding;
EdgeInsetsGeometry _padding;
set padding(EdgeInsetsGeometry value) {
if (padding == value) {
return;
}
_padding = value;
_resolvedPadding = _padding.resolve(_textDirection);
notifyListeners();
}
/// The preferred smallest size the scrollbar thumb can shrink to when the total
/// scrollable extent is large, the current visible viewport is small, and the
/// viewport is not overscrolled.
///
/// The size of the scrollbar may shrink to a smaller size than [minLength] to
/// fit in the available paint area. E.g., when [minLength] is
/// `double.infinity`, it will not be respected if
/// [ScrollMetrics.viewportDimension] and [mainAxisMargin] are finite.
///
/// Mustn't be null and the value has to be greater or equal to
/// [minOverscrollLength], which in turn is >= 0. Defaults to 18.0.
double get minLength => _minLength;
double _minLength;
set minLength(double value) {
if (minLength == value) {
return;
}
_minLength = value;
notifyListeners();
}
/// The preferred smallest size the scrollbar thumb can shrink to when viewport is
/// overscrolled.
///
/// When overscrolling, the size of the scrollbar may shrink to a smaller size
/// than [minOverscrollLength] to fit in the available paint area. E.g., when
/// [minOverscrollLength] is `double.infinity`, it will not be respected if
/// the [ScrollMetrics.viewportDimension] and [mainAxisMargin] are finite.
///
/// The value is less than or equal to [minLength] and greater than or equal to 0.
/// When null, it will default to the value of [minLength].
double get minOverscrollLength => _minOverscrollLength;
double _minOverscrollLength;
set minOverscrollLength(double value) {
if (minOverscrollLength == value) {
return;
}
_minOverscrollLength = value;
notifyListeners();
}
/// {@template flutter.widgets.Scrollbar.scrollbarOrientation}
/// Dictates the orientation of the scrollbar.
///
/// [ScrollbarOrientation.top] places the scrollbar on top of the screen.
/// [ScrollbarOrientation.bottom] places the scrollbar on the bottom of the screen.
/// [ScrollbarOrientation.left] places the scrollbar on the left of the screen.
/// [ScrollbarOrientation.right] places the scrollbar on the right of the screen.
///
/// [ScrollbarOrientation.top] and [ScrollbarOrientation.bottom] can only be
/// used with a vertical scroll.
/// [ScrollbarOrientation.left] and [ScrollbarOrientation.right] can only be
/// used with a horizontal scroll.
///
/// For a vertical scroll the orientation defaults to
/// [ScrollbarOrientation.right] for [TextDirection.ltr] and
/// [ScrollbarOrientation.left] for [TextDirection.rtl].
/// For a horizontal scroll the orientation defaults to [ScrollbarOrientation.bottom].
/// {@endtemplate}
ScrollbarOrientation? get scrollbarOrientation => _scrollbarOrientation;
ScrollbarOrientation? _scrollbarOrientation;
set scrollbarOrientation(ScrollbarOrientation? value) {
if (scrollbarOrientation == value) {
return;
}
_scrollbarOrientation = value;
notifyListeners();
}
/// Whether the painter will be ignored during hit testing.
bool get ignorePointer => _ignorePointer;
bool _ignorePointer;
set ignorePointer(bool value) {
if (ignorePointer == value) {
return;
}
_ignorePointer = value;
notifyListeners();
}
// - Scrollbar Details
Rect? _trackRect;
EdgeInsets? _resolvedPadding;
// The full painted length of the track
double get _trackExtent => _lastMetrics!.viewportDimension - _totalTrackMainAxisOffsets;
// The full length of the track that the thumb can travel
double get _traversableTrackExtent => _trackExtent - (2 * mainAxisMargin);
// Track Offsets
// The track is offset by only padding.
double get _totalTrackMainAxisOffsets =>
_isVertical ? _resolvedPadding!.vertical : _resolvedPadding!.horizontal;
double get _leadingTrackMainAxisOffset => switch (_resolvedOrientation) {
ScrollbarOrientation.left || ScrollbarOrientation.right => _resolvedPadding!.top,
ScrollbarOrientation.top || ScrollbarOrientation.bottom => _resolvedPadding!.left,
};
Rect? _thumbRect;
// The current scroll position + _leadingThumbMainAxisOffset
late double _thumbOffset;
// The fraction visible in relation to the traversable length of the track.
late double _thumbExtent;
// Thumb Offsets
// The thumb is offset by padding and margins.
double get _leadingThumbMainAxisOffset => _leadingTrackMainAxisOffset + mainAxisMargin;
void _setThumbExtent() {
// Thumb extent reflects fraction of content visible, as long as this
// isn't less than the absolute minimum size.
// _totalContentExtent >= viewportDimension, so (_totalContentExtent - _mainAxisPadding) > 0
final double fractionVisible = clampDouble(
(_lastMetrics!.extentInside - _totalTrackMainAxisOffsets) /
(_totalContentExtent - _totalTrackMainAxisOffsets),
0.0,
1.0,
);
final double thumbExtent = math.max(
math.min(_traversableTrackExtent, minOverscrollLength),
_traversableTrackExtent * fractionVisible,
);
final double fractionOverscrolled =
1.0 - _lastMetrics!.extentInside / _lastMetrics!.viewportDimension;
final double safeMinLength = math.min(minLength, _traversableTrackExtent);
final double newMinLength = (_beforeExtent > 0 && _afterExtent > 0)
// Thumb extent is no smaller than minLength if scrolling normally.
? safeMinLength
// User is overscrolling. Thumb extent can be less than minLength
// but no smaller than minOverscrollLength. We can't use the
// fractionVisible to produce intermediate values between minLength and
// minOverscrollLength when the user is transitioning from regular
// scrolling to overscrolling, so we instead use the percentage of the
// content that is still in the viewport to determine the size of the
// thumb. iOS behavior appears to have the thumb reach its minimum size
// with ~20% of overscroll. We map the percentage of minLength from
// [0.8, 1.0] to [0.0, 1.0], so 0% to 20% of overscroll will produce
// values for the thumb that range between minLength and the smallest
// possible value, minOverscrollLength.
: safeMinLength * (1.0 - clampDouble(fractionOverscrolled, 0.0, 0.2) / 0.2);
// The `thumbExtent` should be no greater than `trackSize`, otherwise
// the scrollbar may scroll towards the wrong direction.
_thumbExtent = clampDouble(thumbExtent, newMinLength, _traversableTrackExtent);
}
// - Scrollable Details
ScrollMetrics? _lastMetrics;
bool get _lastMetricsAreScrollable =>
_lastMetrics!.minScrollExtent != _lastMetrics!.maxScrollExtent;
AxisDirection? _lastAxisDirection;
bool get _isVertical =>
_lastAxisDirection == AxisDirection.down || _lastAxisDirection == AxisDirection.up;
bool get _isReversed =>
_lastAxisDirection == AxisDirection.up || _lastAxisDirection == AxisDirection.left;
// The amount of scroll distance before and after the current position.
double get _beforeExtent => _isReversed ? _lastMetrics!.extentAfter : _lastMetrics!.extentBefore;
double get _afterExtent => _isReversed ? _lastMetrics!.extentBefore : _lastMetrics!.extentAfter;
// The total size of the scrollable content.
double get _totalContentExtent {
return _lastMetrics!.maxScrollExtent -
_lastMetrics!.minScrollExtent +
_lastMetrics!.viewportDimension;
}
ScrollbarOrientation get _resolvedOrientation {
if (scrollbarOrientation == null) {
if (_isVertical) {
return textDirection == TextDirection.ltr
? ScrollbarOrientation.right
: ScrollbarOrientation.left;
}
return ScrollbarOrientation.bottom;
}
return scrollbarOrientation!;
}
void _debugAssertIsValidOrientation(ScrollbarOrientation orientation) {
assert(
() {
bool isVerticalOrientation(ScrollbarOrientation orientation) =>
orientation == ScrollbarOrientation.left || orientation == ScrollbarOrientation.right;
return (_isVertical && isVerticalOrientation(orientation)) ||
(!_isVertical && !isVerticalOrientation(orientation));
}(),
'The given ScrollbarOrientation: $orientation is incompatible with the '
'current AxisDirection: $_lastAxisDirection.',
);
}
// - Updating
/// Update with new [ScrollMetrics]. If the metrics change, the scrollbar will
/// show and redraw itself based on these new metrics.
///
/// The scrollbar will remain on screen.
void update(ScrollMetrics metrics, AxisDirection axisDirection) {
if (_lastMetrics != null &&
_lastMetrics!.extentBefore == metrics.extentBefore &&
_lastMetrics!.extentInside == metrics.extentInside &&
_lastMetrics!.extentAfter == metrics.extentAfter &&
_lastAxisDirection == axisDirection) {
return;
}
final ScrollMetrics? oldMetrics = _lastMetrics;
_lastMetrics = metrics;
_lastAxisDirection = axisDirection;
if (!_needPaint(oldMetrics) && !_needPaint(metrics)) {
return;
}
notifyListeners();
}
/// Update and redraw with new scrollbar thickness and radius.
void updateThickness(double nextThickness, Radius nextRadius) {
thickness = nextThickness;
radius = nextRadius;
}
// - Painting
Paint get _paintThumb {
return Paint()..color = color.withOpacity(color.opacity * fadeoutOpacityAnimation.value);
}
bool _needPaint(ScrollMetrics? metrics) {
return metrics != null &&
metrics.maxScrollExtent - metrics.minScrollExtent > precisionErrorTolerance;
}
Paint _paintTrack({bool isBorder = false}) {
if (isBorder) {
return Paint()
..color = trackBorderColor.withOpacity(
trackBorderColor.opacity * fadeoutOpacityAnimation.value,
)
..style = PaintingStyle.stroke
..strokeWidth = 1.0;
}
return Paint()
..color = trackColor.withOpacity(trackColor.opacity * fadeoutOpacityAnimation.value);
}
void _paintScrollbar(Canvas canvas, Size size) {
assert(
textDirection != null,
'A TextDirection must be provided before a Scrollbar can be painted.',
);
final double x, y;
final Size thumbSize, trackSize;
final Offset trackOffset, borderStart, borderEnd;
_debugAssertIsValidOrientation(_resolvedOrientation);
switch (_resolvedOrientation) {
case ScrollbarOrientation.left:
thumbSize = Size(thickness, _thumbExtent);
trackSize = Size(thickness + 2 * crossAxisMargin, _trackExtent);
x = crossAxisMargin + _resolvedPadding!.left;
y = _thumbOffset;
trackOffset = Offset(x - crossAxisMargin, _leadingTrackMainAxisOffset);
borderStart = trackOffset + Offset(trackSize.width, 0.0);
borderEnd = Offset(trackOffset.dx + trackSize.width, trackOffset.dy + _trackExtent);
case ScrollbarOrientation.right:
thumbSize = Size(thickness, _thumbExtent);
trackSize = Size(thickness + 2 * crossAxisMargin, _trackExtent);
x = size.width - thickness - crossAxisMargin - _resolvedPadding!.right;
y = _thumbOffset;
trackOffset = Offset(x - crossAxisMargin, _leadingTrackMainAxisOffset);
borderStart = trackOffset;
borderEnd = Offset(trackOffset.dx, trackOffset.dy + _trackExtent);
case ScrollbarOrientation.top:
thumbSize = Size(_thumbExtent, thickness);
trackSize = Size(_trackExtent, thickness + 2 * crossAxisMargin);
x = _thumbOffset;
y = crossAxisMargin + _resolvedPadding!.top;
trackOffset = Offset(_leadingTrackMainAxisOffset, y - crossAxisMargin);
borderStart = trackOffset + Offset(0.0, trackSize.height);
borderEnd = Offset(trackOffset.dx + _trackExtent, trackOffset.dy + trackSize.height);
case ScrollbarOrientation.bottom:
thumbSize = Size(_thumbExtent, thickness);
trackSize = Size(_trackExtent, thickness + 2 * crossAxisMargin);
x = _thumbOffset;
y = size.height - thickness - crossAxisMargin - _resolvedPadding!.bottom;
trackOffset = Offset(_leadingTrackMainAxisOffset, y - crossAxisMargin);
borderStart = trackOffset;
borderEnd = Offset(trackOffset.dx + _trackExtent, trackOffset.dy);
}
// Whether we paint or not, calculating these rects allows us to hit test
// when the scrollbar is transparent.
_trackRect = trackOffset & trackSize;
_thumbRect = Offset(x, y) & thumbSize;
// Paint if the opacity dictates visibility
if (fadeoutOpacityAnimation.value != 0.0) {
// Track
if (trackRadius == null) {
canvas.drawRect(_trackRect!, _paintTrack());
} else {
canvas.drawRRect(RRect.fromRectAndRadius(_trackRect!, trackRadius!), _paintTrack());
}
// Track Border
canvas.drawLine(borderStart, borderEnd, _paintTrack(isBorder: true));
if (radius != null) {
// Rounded rect thumb
canvas.drawRRect(RRect.fromRectAndRadius(_thumbRect!, radius!), _paintThumb);
return;
}
if (shape == null) {
// Square thumb
canvas.drawRect(_thumbRect!, _paintThumb);
return;
}
// Custom-shaped thumb
if (shape!.preferPaintInterior) {
shape!.paintInterior(canvas, _thumbRect!, _paintThumb);
} else {
final Path outerPath = shape!.getOuterPath(_thumbRect!);
canvas.drawPath(outerPath, _paintThumb);
}
shape!.paint(canvas, _thumbRect!);
}
}
@override
void paint(Canvas canvas, Size size) {
if (_lastAxisDirection == null || !_needPaint(_lastMetrics)) {
return;
}
// Skip painting if there's not enough space.
if (_traversableTrackExtent <= 0) {
return;
}
// Do not paint a scrollbar if the scroll view is infinitely long.
// TODO(Piinks): Special handling for infinite scroll views,
// https://github.com/flutter/flutter/issues/41434
if (_lastMetrics!.maxScrollExtent.isInfinite) {
return;
}
_setThumbExtent();
final double thumbPositionOffset = _getScrollToTrack(_lastMetrics!, _thumbExtent);
_thumbOffset = thumbPositionOffset + _leadingThumbMainAxisOffset;
return _paintScrollbar(canvas, size);
}
// - Scroll Position Conversion
/// Convert between a thumb track position and the corresponding scroll
/// position.
///
/// The `thumbOffsetLocal` argument is a position in the thumb track.
double getTrackToScroll(double thumbOffsetLocal) {
final double scrollableExtent = _lastMetrics!.maxScrollExtent - _lastMetrics!.minScrollExtent;
final double thumbMovableExtent = _traversableTrackExtent - _thumbExtent;
return scrollableExtent * thumbOffsetLocal / thumbMovableExtent;
}
/// The thumb's corresponding scroll offset in the track.
double getThumbScrollOffset() {
assert(_lastMetrics!.maxScrollExtent.isFinite && _lastMetrics!.minScrollExtent.isFinite);
final double scrollableExtent = _lastMetrics!.maxScrollExtent - _lastMetrics!.minScrollExtent;
final double maxFraction = _lastMetrics!.maxScrollExtent / scrollableExtent;
final double minFraction = _lastMetrics!.minScrollExtent / scrollableExtent;
final double fractionPast = (scrollableExtent > 0)
? clampDouble(_lastMetrics!.pixels / scrollableExtent, minFraction, maxFraction)
: 0;
return fractionPast * (_traversableTrackExtent - _thumbExtent);
}
// Converts between a scroll position and the corresponding position in the
// thumb track.
double _getScrollToTrack(ScrollMetrics metrics, double thumbExtent) {
final double scrollableExtent = metrics.maxScrollExtent - metrics.minScrollExtent;
final double fractionPast = (scrollableExtent > 0)
? clampDouble((metrics.pixels - metrics.minScrollExtent) / scrollableExtent, 0.0, 1.0)
: 0;
return (_isReversed ? 1 - fractionPast : fractionPast) *
(_traversableTrackExtent - thumbExtent);
}
// - Hit Testing
@override
bool? hitTest(Offset? position) {
// There is nothing painted to hit.
if (_thumbRect == null) {
return null;
}
// Interaction disabled.
if (ignorePointer
// The thumb is not able to be hit when transparent.
||
fadeoutOpacityAnimation.value == 0.0
// Not scrollable
||
!_lastMetricsAreScrollable) {
return false;
}
return _trackRect!.contains(position!);
}
/// Same as hitTest, but includes some padding when the [PointerEvent] is
/// caused by [PointerDeviceKind.touch] to make sure that the region
/// isn't too small to be interacted with by the user.
///
/// The hit test area for hovering with [PointerDeviceKind.mouse] over the
/// scrollbar also uses this extra padding. This is to make it easier to
/// interact with the scrollbar by presenting it to the mouse for interaction
/// based on proximity. When `forHover` is true, the larger hit test area will
/// be used.
bool hitTestInteractive(Offset position, PointerDeviceKind kind, {bool forHover = false}) {
if (_trackRect == null) {
// We have not computed the scrollbar position yet.
return false;
}
if (ignorePointer) {
return false;
}
if (!_lastMetricsAreScrollable) {
return false;
}
final Rect interactiveRect = _trackRect!;
final Rect paddedRect = interactiveRect.expandToInclude(
Rect.fromCircle(center: _thumbRect!.center, radius: _kMinInteractiveSize / 2),
);
// The scrollbar is not able to be hit when transparent - except when
// hovering with a mouse. This should bring the scrollbar into view so the
// mouse can interact with it.
if (fadeoutOpacityAnimation.value == 0.0) {
if (forHover && kind == PointerDeviceKind.mouse) {
return paddedRect.contains(position);
}
return false;
}
switch (kind) {
case PointerDeviceKind.touch:
case PointerDeviceKind.trackpad:
return paddedRect.contains(position);
case PointerDeviceKind.mouse:
case PointerDeviceKind.stylus:
case PointerDeviceKind.invertedStylus:
case PointerDeviceKind.unknown:
return interactiveRect.contains(position);
}
}
/// Same as hitTestInteractive, but excludes the track portion of the scrollbar.
/// Used to evaluate interactions with only the scrollbar thumb.
bool hitTestOnlyThumbInteractive(Offset position, PointerDeviceKind kind) {
if (_thumbRect == null) {
return false;
}
if (ignorePointer) {
return false;
}
// The thumb is not able to be hit when transparent.
if (fadeoutOpacityAnimation.value == 0.0) {
return false;
}
if (!_lastMetricsAreScrollable) {
return false;
}
switch (kind) {
case PointerDeviceKind.touch:
case PointerDeviceKind.trackpad:
final Rect touchThumbRect = _thumbRect!.expandToInclude(
Rect.fromCircle(center: _thumbRect!.center, radius: _kMinInteractiveSize / 2),
);
return touchThumbRect.contains(position);
case PointerDeviceKind.mouse:
case PointerDeviceKind.stylus:
case PointerDeviceKind.invertedStylus:
case PointerDeviceKind.unknown:
return _thumbRect!.contains(position);
}
}
@override
bool shouldRepaint(ScrollbarPainter oldDelegate) {
// Should repaint if any properties changed.
return color != oldDelegate.color ||
trackColor != oldDelegate.trackColor ||
trackBorderColor != oldDelegate.trackBorderColor ||
textDirection != oldDelegate.textDirection ||
thickness != oldDelegate.thickness ||
fadeoutOpacityAnimation != oldDelegate.fadeoutOpacityAnimation ||
mainAxisMargin != oldDelegate.mainAxisMargin ||
crossAxisMargin != oldDelegate.crossAxisMargin ||
radius != oldDelegate.radius ||
trackRadius != oldDelegate.trackRadius ||
shape != oldDelegate.shape ||
padding != oldDelegate.padding ||
minLength != oldDelegate.minLength ||
minOverscrollLength != oldDelegate.minOverscrollLength ||
scrollbarOrientation != oldDelegate.scrollbarOrientation ||
ignorePointer != oldDelegate.ignorePointer;
}
@override
bool shouldRebuildSemantics(CustomPainter oldDelegate) => false;
@override
SemanticsBuilderCallback? get semanticsBuilder => null;
@override
String toString() => describeIdentity(this);
@override
void dispose() {
fadeoutOpacityAnimation.removeListener(notifyListeners);
super.dispose();
}
}
/// An extendable base class for building scrollbars that fade in and out.
///
/// To add a scrollbar to a [ScrollView], like a [ListView] or a
/// [CustomScrollView], wrap the scroll view widget in a [RawScrollbar] widget.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=DbkIQSvwnZc}
///
/// {@template flutter.widgets.Scrollbar}
/// A scrollbar thumb indicates which portion of a [ScrollView] is actually
/// visible.
///
/// By default, the thumb will fade in and out as the child scroll view
/// scrolls. When [thumbVisibility] is true, the scrollbar thumb will remain
/// visible without the fade animation. This requires that the [ScrollController]
/// associated with the Scrollable widget is provided to [controller], or that
/// the [PrimaryScrollController] is being used by that Scrollable widget.
///
/// If the scrollbar is wrapped around multiple [ScrollView]s, it only responds to
/// the nearest ScrollView and shows the corresponding scrollbar thumb by default.
/// The [notificationPredicate] allows the ability to customize which
/// [ScrollNotification]s the Scrollbar should listen to.
///
/// If the child [ScrollView] is infinitely long, the [RawScrollbar] will not be
/// painted. In this case, the scrollbar cannot accurately represent the
/// relative location of the visible area, or calculate the accurate delta to
/// apply when dragging on the thumb or tapping on the track.
///
/// ### Interaction
///
/// Scrollbars are interactive and can use the [PrimaryScrollController] if
/// a [controller] is not set. Interactive Scrollbar thumbs can be dragged along
/// the main axis of the [ScrollView] to change the [ScrollPosition]. Tapping
/// along the track exclusive of the thumb will trigger a
/// [ScrollIncrementType.page] based on the relative position to the thumb.
///
/// When using the [PrimaryScrollController], it must not be attached to more
/// than one [ScrollPosition]. [ScrollView]s that have not been provided a
/// [ScrollController] and have a [ScrollView.scrollDirection] of
/// [Axis.vertical] will automatically attach their ScrollPosition to the
/// PrimaryScrollController. Provide a unique ScrollController to each
/// [Scrollable] in this case to prevent having multiple ScrollPositions
/// attached to the PrimaryScrollController.
///
/// <callout-box>
///
/// This sample shows an app with two scrollables in the same route. Since by
/// default, there is one [PrimaryScrollController] per route, and they both have a
/// scroll direction of [Axis.vertical], they would both try to attach to that
/// controller on mobile platforms. The [Scrollbar] cannot support multiple
/// positions attached to the same controller, so one [ListView], and its
/// [Scrollbar] have been provided a unique [ScrollController]. Desktop
/// platforms do not automatically attach to the PrimaryScrollController,
/// requiring [ScrollView.primary] to be true instead in order to use the
/// PrimaryScrollController.
///
/// Alternatively, a new PrimaryScrollController could be created above one of
/// the [ListView]s.
///
// TODO(framework): Replace the following block with a @dartpad directive
// when it's supported. https://github.com/dart-lang/dartdoc/issues/4123
/// <small>
///
/// To see it in action, copy and run this code snippet on [DartPad](https://dartpad.dev/).
///
/// </small>
///
/// {@example /examples/api/lib/widgets/scrollbar/raw_scrollbar.0.dart#body}
///
/// </callout-box>
///
/// ### Automatic Scrollbars on Desktop Platforms
///
/// Scrollbars are added to most [Scrollable] widgets by default on
/// [TargetPlatformVariant.desktop] platforms. This is done through
/// [ScrollBehavior.buildScrollbar] as part of an app's
/// [ScrollConfiguration]. Scrollables that do not use the
/// [PrimaryScrollController] or have a [ScrollController] provided to them
/// will receive a unique ScrollController for use with the Scrollbar. In this
/// case, only one Scrollable can be using the PrimaryScrollController, unless
/// [interactive] is false. To prevent [Axis.vertical] Scrollables from using
/// the PrimaryScrollController, set [ScrollView.primary] to false. Scrollable
/// widgets that do not have automatically applied Scrollbars include
///
/// * [EditableText]
/// * [ListWheelScrollView]
/// * [PageView]
/// * [NestedScrollView]
/// * [DropdownButton]
///
/// Default Scrollbars can be disabled for the whole app by setting a
/// [ScrollBehavior] with `scrollbars` set to false.
///
/// <callout-box>
///
// TODO(framework): Add unit tests to this code snippet.
// https://github.com/flutter/flutter/issues/188530
///
/// ```dart
/// MaterialApp(
/// scrollBehavior: const MaterialScrollBehavior()
/// .copyWith(scrollbars: false),
/// home: Scaffold(
/// appBar: AppBar(title: const Text('Home')),
/// ),
/// )
/// ```
///
/// </callout-box>
///
/// <callout-box>
///
/// This sample shows how to disable the default Scrollbar for a [Scrollable]
/// widget to avoid duplicate Scrollbars when running on desktop platforms.
///
// TODO(framework): Replace the following block with a @dartpad directive
// when it's supported. https://github.com/dart-lang/dartdoc/issues/4123
/// <small>
///
/// To see it in action, copy and run this code snippet on [DartPad](https://dartpad.dev/).
///
/// </small>
///
/// {@example /examples/api/lib/widgets/scrollbar/raw_scrollbar.desktop.0.dart#body}
///
/// </callout-box>
/// {@endtemplate}
///
/// {@tool dartpad}
/// This sample shows a [RawScrollbar] that executes a fade animation as
/// scrolling occurs. The RawScrollbar will fade into view as the user scrolls,
/// and fade out when scrolling stops. The [GridView] uses the
/// [PrimaryScrollController] since it has an [Axis.vertical] scroll direction
/// and has not been provided a [ScrollController].
///
/// ** See code in examples/api/lib/widgets/scrollbar/raw_scrollbar.1.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// When `thumbVisibility` is true, the scrollbar thumb will remain visible without
/// the fade animation. This requires that a [ScrollController] is provided to
/// `controller` for both the [RawScrollbar] and the [GridView].
/// Alternatively, the [PrimaryScrollController] can be used automatically so long
/// as it is attached to the singular [ScrollPosition] associated with the GridView.
///
/// ** See code in examples/api/lib/widgets/scrollbar/raw_scrollbar.2.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ListView], which displays a linear, scrollable list of children.
/// * [GridView], which displays a 2 dimensional, scrollable array of children.