-
Notifications
You must be signed in to change notification settings - Fork 30.3k
Expand file tree
/
Copy pathtabs.dart
More file actions
2944 lines (2635 loc) · 103 KB
/
tabs.dart
File metadata and controls
2944 lines (2635 loc) · 103 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 'no_splash.dart';
library;
import 'dart:math' as math;
import 'dart:ui' show SemanticsRole, lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart' show DragStartBehavior;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'app_bar.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'constants.dart';
import 'debug.dart';
import 'ink_well.dart';
import 'material.dart';
import 'material_localizations.dart';
import 'tab_bar_theme.dart';
import 'tab_controller.dart';
import 'tab_indicator.dart';
import 'text_theme.dart';
import 'theme.dart';
const double _kTabHeight = 46.0;
const double _kTextAndIconTabHeight = 72.0;
const double _kStartOffset = 52.0;
/// Defines how the bounds of the selected tab indicator are computed.
///
/// See also:
///
/// * [TabBar], which displays a row of tabs.
/// * [TabBarView], which displays a widget for the currently selected tab.
/// * [TabBar.indicator], which defines the appearance of the selected tab
/// indicator relative to the tab's bounds.
enum TabBarIndicatorSize {
/// The tab indicator's bounds are as wide as the space occupied by the tab
/// in the tab bar: from the right edge of the previous tab to the left edge
/// of the next tab.
tab,
/// The tab's bounds are only as wide as the (centered) tab widget itself.
///
/// This value is used to align the tab's label, typically a [Tab]
/// widget's text or icon, with the selected tab indicator.
label,
}
/// Defines how tabs are aligned horizontally in a [TabBar].
///
/// See also:
///
/// * [TabBar], which displays a row of tabs.
/// * [TabBarView], which displays a widget for the currently selected tab.
/// * [TabBar.tabAlignment], which defines the horizontal alignment of the
/// tabs within the [TabBar].
enum TabAlignment {
// TODO(tahatesser): Add a link to the Material Design spec for
// horizontal offset when it is available.
// It's currently sourced from androidx/compose/material3/TabRow.kt.
/// If [TabBar.isScrollable] is true, tabs are aligned to the
/// start of the [TabBar]. Otherwise throws an exception.
///
/// It is not recommended to set [TabAlignment.start] when
/// [ThemeData.useMaterial3] is false.
start,
/// If [TabBar.isScrollable] is true, tabs are aligned to the
/// start of the [TabBar] with an offset of 52.0 pixels.
/// Otherwise throws an exception.
///
/// It is not recommended to set [TabAlignment.startOffset] when
/// [ThemeData.useMaterial3] is false.
startOffset,
/// If [TabBar.isScrollable] is false, tabs are stretched to fill the
/// [TabBar]. Otherwise throws an exception.
fill,
/// Tabs are aligned to the center of the [TabBar].
center,
}
/// Defines how the tab indicator animates when the selected tab changes.
///
/// See also:
/// * [TabBar], which displays a row of tabs.
/// * [TabBarThemeData], which can be used to configure the appearance of the tab
/// indicator.
enum TabIndicatorAnimation {
/// The tab indicator animates linearly.
linear,
/// The tab indicator animates with an elastic effect.
elastic,
}
/// A Material Design [TabBar] tab.
///
/// If both [icon] and [text] are provided, the text is displayed below
/// the icon.
///
/// See also:
///
/// * [TabBar], which displays a row of tabs.
/// * [TabBarView], which displays a widget for the currently selected tab.
/// * [TabController], which coordinates tab selection between a [TabBar] and a [TabBarView].
/// * <https://material.io/design/components/tabs.html>
class Tab extends StatelessWidget implements PreferredSizeWidget {
/// Creates a Material Design [TabBar] tab.
///
/// At least one of [text], [icon], and [child] must be non-null. The [text]
/// and [child] arguments must not be used at the same time. The
/// [iconMargin] is only useful when [icon] and either one of [text] or
/// [child] is non-null.
const Tab({super.key, this.text, this.icon, this.iconMargin, this.height, this.child})
: assert(
text != null || child != null || icon != null,
'Tab requires at least one of text, child, or icon to be non-null.',
),
assert(
text == null || child == null,
'Provide either text or child, not both, when creating a Tab.',
);
/// The text to display as the tab's label.
///
/// Must not be used in combination with [child].
final String? text;
/// The widget to be used as the tab's label.
///
/// Usually a [Text] widget, possibly wrapped in a [Semantics] widget.
///
/// Must not be used in combination with [text].
final Widget? child;
/// An icon to display as the tab's label.
final Widget? icon;
/// The margin added around the tab's icon.
///
/// Only useful when used in combination with [icon], and either one of
/// [text] or [child] is non-null.
///
/// Defaults to 2 pixels of bottom margin. If [ThemeData.useMaterial3] is false,
/// then defaults to 10 pixels of bottom margin.
final EdgeInsetsGeometry? iconMargin;
/// The height of the [Tab].
///
/// If null, the height will be calculated based on the content of the [Tab]. When `icon` is not
/// null along with `child` or `text`, the default height is 72.0 pixels. Without an `icon`, the
/// height is 46.0 pixels.
///
/// {@tool snippet}
///
/// The provided tab height cannot be lower than the default height. Use
/// [PreferredSize] widget to adjust the overall [TabBar] height and match
/// the provided tab [height]:
///
/// ```dart
/// bottom: const PreferredSize(
/// preferredSize: Size.fromHeight(20.0),
/// child: TabBar(
/// tabs: <Widget>[
/// Tab(
/// text: 'Tab 1',
/// height: 20.0,
/// ),
/// Tab(
/// text: 'Tab 2',
/// height: 20.0,
/// ),
/// ],
/// ),
/// ),
/// ```
/// {@end-tool}
final double? height;
Widget _buildLabelText() {
return child ?? Text(text!, softWrap: false, overflow: TextOverflow.fade);
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterial(context));
final double calculatedHeight;
final Widget label;
if (icon == null) {
calculatedHeight = _kTabHeight;
label = _buildLabelText();
} else if (text == null && child == null) {
calculatedHeight = _kTabHeight;
label = icon!;
} else {
calculatedHeight = _kTextAndIconTabHeight;
final EdgeInsetsGeometry effectiveIconMargin =
iconMargin ??
(Theme.of(context).useMaterial3
? _TabsPrimaryDefaultsM3.iconMargin
: _TabsDefaultsM2.iconMargin);
label = Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(padding: effectiveIconMargin, child: icon),
_buildLabelText(),
],
);
}
return SizedBox(
height: height ?? calculatedHeight,
child: Center(widthFactor: 1.0, child: label),
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(StringProperty('text', text, defaultValue: null));
}
@override
Size get preferredSize {
if (height != null) {
return Size.fromHeight(height!);
} else if ((text != null || child != null) && icon != null) {
return const Size.fromHeight(_kTextAndIconTabHeight);
} else {
return const Size.fromHeight(_kTabHeight);
}
}
}
class _TabStyle extends AnimatedWidget {
const _TabStyle({
required Animation<double> animation,
required this.isSelected,
required this.isPrimary,
required this.labelColor,
required this.unselectedLabelColor,
required this.labelStyle,
required this.unselectedLabelStyle,
required this.defaults,
required this.child,
}) : super(listenable: animation);
final TextStyle? labelStyle;
final TextStyle? unselectedLabelStyle;
final bool isSelected;
final bool isPrimary;
final Color? labelColor;
final Color? unselectedLabelColor;
final TabBarThemeData defaults;
final Widget child;
WidgetStateColor _resolveWithLabelColor(BuildContext context, {IconThemeData? iconTheme}) {
final ThemeData themeData = Theme.of(context);
final TabBarThemeData tabBarTheme = TabBarTheme.of(context);
final animation = listenable as Animation<double>;
// labelStyle.color (and tabBarTheme.labelStyle.color) is not considered
// as it'll be a breaking change without a possible migration plan. for
// details: https://github.com/flutter/flutter/pull/109541#issuecomment-1294241417
Color selectedColor =
labelColor ??
tabBarTheme.labelColor ??
labelStyle?.color ??
tabBarTheme.labelStyle?.color ??
defaults.labelColor!;
final Color unselectedColor;
if (selectedColor is WidgetStateColor) {
unselectedColor = selectedColor.resolve(const <WidgetState>{});
selectedColor = selectedColor.resolve(const <WidgetState>{WidgetState.selected});
} else {
// unselectedLabelColor and tabBarTheme.unselectedLabelColor are ignored
// when labelColor is a WidgetStateColor.
unselectedColor =
unselectedLabelColor ??
tabBarTheme.unselectedLabelColor ??
unselectedLabelStyle?.color ??
tabBarTheme.unselectedLabelStyle?.color ??
iconTheme?.color ??
(themeData.useMaterial3
? defaults.unselectedLabelColor!
: selectedColor.withAlpha(0xB2)); // 70% alpha
}
return WidgetStateColor.resolveWith((Set<WidgetState> states) {
if (states.contains(WidgetState.selected)) {
return Color.lerp(selectedColor, unselectedColor, animation.value)!;
}
return Color.lerp(unselectedColor, selectedColor, animation.value)!;
});
}
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final TabBarThemeData tabBarTheme = TabBarTheme.of(context);
final animation = listenable as Animation<double>;
final states = isSelected ? const <WidgetState>{WidgetState.selected} : const <WidgetState>{};
// To enable TextStyle.lerp(style1, style2, value), both styles must have
// the same value of inherit. Force that to be inherit=true here.
final TextStyle selectedStyle = defaults.labelStyle!
.merge(labelStyle ?? tabBarTheme.labelStyle)
.copyWith(inherit: true);
final TextStyle unselectedStyle = defaults.unselectedLabelStyle!
.merge(unselectedLabelStyle ?? tabBarTheme.unselectedLabelStyle ?? labelStyle)
.copyWith(inherit: true);
final TextStyle textStyle = isSelected
? TextStyle.lerp(selectedStyle, unselectedStyle, animation.value)!
: TextStyle.lerp(unselectedStyle, selectedStyle, animation.value)!;
final Color defaultIconColor = switch (theme.colorScheme.brightness) {
Brightness.light => kDefaultIconDarkColor,
Brightness.dark => kDefaultIconLightColor,
};
final IconThemeData? customIconTheme = switch (IconTheme.of(context)) {
final IconThemeData iconTheme when iconTheme.color != defaultIconColor => iconTheme,
_ => null,
};
final Color iconColor = _resolveWithLabelColor(
context,
iconTheme: customIconTheme,
).resolve(states);
final Color labelColor = _resolveWithLabelColor(context).resolve(states);
return DefaultTextStyle(
style: textStyle.copyWith(color: labelColor),
child: IconTheme.merge(
data: IconThemeData(size: customIconTheme?.size ?? 24.0, color: iconColor),
child: child,
),
);
}
}
typedef _LayoutCallback =
void Function(List<double> xOffsets, TextDirection textDirection, double width);
class _TabLabelBarRenderer extends RenderFlex {
_TabLabelBarRenderer({
required super.direction,
required super.mainAxisSize,
required super.mainAxisAlignment,
required super.crossAxisAlignment,
required TextDirection super.textDirection,
required super.verticalDirection,
required this.onPerformLayout,
});
_LayoutCallback onPerformLayout;
@override
void performLayout() {
super.performLayout();
// xOffsets will contain childCount+1 values, giving the offsets of the
// leading edge of the first tab as the first value, of the leading edge of
// the each subsequent tab as each subsequent value, and of the trailing
// edge of the last tab as the last value.
RenderBox? child = firstChild;
final xOffsets = <double>[];
while (child != null) {
final childParentData = child.parentData! as FlexParentData;
xOffsets.add(childParentData.offset.dx);
assert(child.parentData == childParentData);
child = childParentData.nextSibling;
}
assert(textDirection != null);
switch (textDirection!) {
case TextDirection.rtl:
xOffsets.insert(0, size.width);
case TextDirection.ltr:
xOffsets.add(size.width);
}
onPerformLayout(xOffsets, textDirection!, size.width);
}
}
// This class and its renderer class only exist to report the widths of the tabs
// upon layout. The tab widths are only used at paint time (see _IndicatorPainter)
// or in response to input.
class _TabLabelBar extends Flex {
const _TabLabelBar({super.children, required this.onPerformLayout, required super.mainAxisSize})
: super(
direction: Axis.horizontal,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
verticalDirection: VerticalDirection.down,
);
final _LayoutCallback onPerformLayout;
@override
RenderFlex createRenderObject(BuildContext context) {
return _TabLabelBarRenderer(
direction: direction,
mainAxisAlignment: mainAxisAlignment,
mainAxisSize: mainAxisSize,
crossAxisAlignment: crossAxisAlignment,
textDirection: getEffectiveTextDirection(context)!,
verticalDirection: verticalDirection,
onPerformLayout: onPerformLayout,
);
}
@override
void updateRenderObject(BuildContext context, _TabLabelBarRenderer renderObject) {
super.updateRenderObject(context, renderObject);
renderObject.onPerformLayout = onPerformLayout;
}
}
double _indexChangeProgress(TabController controller) {
final double controllerValue = controller.animation!.value;
final double previousIndex = controller.previousIndex.toDouble();
final double currentIndex = controller.index.toDouble();
// The controller's offset is changing because the user is dragging the
// TabBarView's PageView to the left or right.
if (!controller.indexIsChanging) {
return clampDouble((currentIndex - controllerValue).abs(), 0.0, 1.0);
}
// The TabController animation's value is changing from previousIndex to currentIndex.
return (controllerValue - currentIndex).abs() / (currentIndex - previousIndex).abs();
}
class _DividerPainter extends CustomPainter {
_DividerPainter({required this.dividerColor, required this.dividerHeight});
final Color dividerColor;
final double dividerHeight;
@override
void paint(Canvas canvas, Size size) {
if (dividerHeight <= 0.0) {
return;
}
final paint = Paint()
..color = dividerColor
..strokeWidth = dividerHeight;
canvas.drawLine(
Offset(0, size.height - (paint.strokeWidth / 2)),
Offset(size.width, size.height - (paint.strokeWidth / 2)),
paint,
);
}
@override
bool shouldRepaint(_DividerPainter oldDelegate) {
return oldDelegate.dividerColor != dividerColor || oldDelegate.dividerHeight != dividerHeight;
}
}
// A ChangeNotifier for triggering repaints when async resources load.
class _IndicatorPainterNotifier extends ChangeNotifier {
void notify() {
notifyListeners();
}
@override
String toString() => describeIdentity(this);
}
class _IndicatorPainter extends CustomPainter {
factory _IndicatorPainter({
required TabController controller,
required Decoration indicator,
required TabBarIndicatorSize indicatorSize,
required List<GlobalKey> tabKeys,
required _IndicatorPainter? old,
required EdgeInsetsGeometry indicatorPadding,
required List<EdgeInsetsGeometry> labelPaddings,
Color? dividerColor,
double? dividerHeight,
required bool showDivider,
double? devicePixelRatio,
required TabIndicatorAnimation indicatorAnimation,
required TextDirection textDirection,
}) {
/// Initializing [_IndicatorPainterNotifier] here that allows the
/// repaint notifier to be used in the super constructor call
/// (within [Listenable.merge]) while also being stored as a private field.
///
/// The notifier is to trigger a repaint when asynchronous resources,
/// like images in the indicator [Decoration], are finished loading.
return _IndicatorPainter._(
controller: controller,
indicator: indicator,
indicatorSize: indicatorSize,
tabKeys: tabKeys,
old: old,
indicatorPadding: indicatorPadding,
labelPaddings: labelPaddings,
dividerColor: dividerColor,
dividerHeight: dividerHeight,
showDivider: showDivider,
devicePixelRatio: devicePixelRatio,
indicatorAnimation: indicatorAnimation,
textDirection: textDirection,
repaint: _IndicatorPainterNotifier(),
);
}
_IndicatorPainter._({
required this.controller,
required this.indicator,
required this.indicatorSize,
required this.tabKeys,
required _IndicatorPainter? old,
required this.indicatorPadding,
required this.labelPaddings,
this.dividerColor,
this.dividerHeight,
required this.showDivider,
this.devicePixelRatio,
required this.indicatorAnimation,
required this.textDirection,
required _IndicatorPainterNotifier repaint,
}) : _repaint = repaint,
super(repaint: Listenable.merge(<Listenable?>[controller.animation, repaint])) {
assert(debugMaybeDispatchCreated('material', '_IndicatorPainter', this));
if (old != null) {
saveTabOffsets(old._currentTabOffsets, old._currentTextDirection);
}
}
final TabController controller;
final Decoration indicator;
final TabBarIndicatorSize indicatorSize;
final EdgeInsetsGeometry indicatorPadding;
final List<GlobalKey> tabKeys;
final List<EdgeInsetsGeometry> labelPaddings;
final Color? dividerColor;
final double? dividerHeight;
final bool showDivider;
final double? devicePixelRatio;
final TabIndicatorAnimation indicatorAnimation;
final TextDirection textDirection;
final _IndicatorPainterNotifier _repaint;
// _currentTabOffsets and _currentTextDirection are set each time TabBar
// layout is completed. These values can be null when TabBar contains no
// tabs, since there are nothing to lay out.
List<double>? _currentTabOffsets;
TextDirection? _currentTextDirection;
Rect? _currentRect;
BoxPainter? _painter;
bool _needsPaint = false;
void markNeedsPaint() {
_needsPaint = true;
_repaint.notify();
}
void dispose() {
assert(debugMaybeDispatchDisposed(this));
_painter?.dispose();
_repaint.dispose();
}
void saveTabOffsets(List<double>? tabOffsets, TextDirection? textDirection) {
_currentTabOffsets = tabOffsets;
_currentTextDirection = textDirection;
}
// _currentTabOffsets[index] is the offset of the start edge of the tab at index, and
// _currentTabOffsets[_currentTabOffsets.length] is the end edge of the last tab.
int get maxTabIndex => _currentTabOffsets!.length - 2;
double centerOf(int tabIndex) {
assert(_currentTabOffsets != null);
assert(_currentTabOffsets!.isNotEmpty);
assert(tabIndex >= 0);
assert(tabIndex <= maxTabIndex);
return (_currentTabOffsets![tabIndex] + _currentTabOffsets![tabIndex + 1]) / 2.0;
}
Rect indicatorRect(Size tabBarSize, int tabIndex) {
assert(_currentTabOffsets != null);
assert(_currentTextDirection != null);
assert(_currentTabOffsets!.isNotEmpty);
assert(tabIndex >= 0);
assert(tabIndex <= maxTabIndex);
double tabLeft, tabRight;
(tabLeft, tabRight) = switch (_currentTextDirection!) {
TextDirection.rtl => (_currentTabOffsets![tabIndex + 1], _currentTabOffsets![tabIndex]),
TextDirection.ltr => (_currentTabOffsets![tabIndex], _currentTabOffsets![tabIndex + 1]),
};
if (indicatorSize == TabBarIndicatorSize.label) {
final double tabWidth = tabKeys[tabIndex].currentContext!.size!.width;
final EdgeInsetsGeometry labelPadding = labelPaddings[tabIndex];
final EdgeInsets insets = labelPadding.resolve(_currentTextDirection);
final double delta = ((tabRight - tabLeft) - (tabWidth + insets.horizontal)) / 2.0;
tabLeft += delta + insets.left;
tabRight = tabLeft + tabWidth;
}
final EdgeInsets insets = indicatorPadding.resolve(_currentTextDirection);
final rect = Rect.fromLTWH(tabLeft, 0.0, tabRight - tabLeft, tabBarSize.height);
if (!(rect.size >= insets.collapsedSize)) {
throw FlutterError(
'indicatorPadding insets should be less than Tab Size\n'
'Rect Size : ${rect.size}, Insets: $insets',
);
}
return insets.deflateRect(rect);
}
@override
void paint(Canvas canvas, Size size) {
_needsPaint = false;
_painter ??= indicator.createBoxPainter(markNeedsPaint);
final double value = controller.animation!.value;
_currentRect = switch (indicatorAnimation) {
TabIndicatorAnimation.linear => _applyLinearEffect(size: size, value: value),
TabIndicatorAnimation.elastic => _applyElasticEffect(size: size, value: value),
};
assert(_currentRect != null);
final configuration = ImageConfiguration(
size: _currentRect!.size,
textDirection: _currentTextDirection,
devicePixelRatio: devicePixelRatio,
);
if (showDivider && dividerHeight! > 0) {
final dividerPaint = Paint()
..color = dividerColor!
..strokeWidth = dividerHeight!;
final dividerP1 = Offset(0, size.height - (dividerPaint.strokeWidth / 2));
final dividerP2 = Offset(size.width, size.height - (dividerPaint.strokeWidth / 2));
canvas.drawLine(dividerP1, dividerP2, dividerPaint);
}
_painter!.paint(canvas, _currentRect!.topLeft, configuration);
}
/// Applies the linear effect to the indicator.
Rect? _applyLinearEffect({required Size size, required double value}) {
final double index = controller.index.toDouble();
final bool ltr = index > value;
final int from = (ltr ? value.floor() : value.ceil()).clamp(0, maxTabIndex);
final int to = (ltr ? from + 1 : from - 1).clamp(0, maxTabIndex);
final Rect fromRect = indicatorRect(size, from);
final Rect toRect = indicatorRect(size, to);
return Rect.lerp(fromRect, toRect, (value - from).abs());
}
// Ease out sine (decelerating).
double decelerateInterpolation(double fraction) {
return math.sin((fraction * math.pi) / 2.0);
}
// Ease in sine (accelerating).
double accelerateInterpolation(double fraction) {
return 1.0 - math.cos((fraction * math.pi) / 2.0);
}
/// Applies the elastic effect to the indicator.
Rect? _applyElasticEffect({required Size size, required double value}) {
final double index = controller.index.toDouble();
double progressLeft = (index - value).abs();
final int to = progressLeft == 0.0 || !controller.indexIsChanging
? switch (textDirection) {
TextDirection.ltr => value.ceil(),
TextDirection.rtl => value.floor(),
}.clamp(0, maxTabIndex)
: controller.index;
final int from = progressLeft == 0.0 || !controller.indexIsChanging
? switch (textDirection) {
TextDirection.ltr => (to - 1),
TextDirection.rtl => (to + 1),
}.clamp(0, maxTabIndex)
: controller.previousIndex;
final Rect toRect = indicatorRect(size, to);
final Rect fromRect = indicatorRect(size, from);
final Rect rect = Rect.lerp(fromRect, toRect, (value - from).abs())!;
// If the tab animation is completed, there is no need to stretch the indicator
// This only works for the tab change animation via tab index, not when
// dragging a [TabBarView], but it's still ok, to avoid unnecessary calculations.
if (controller.animation!.isCompleted) {
return rect;
}
final double tabChangeProgress;
if (controller.indexIsChanging) {
final int tabsDelta = (controller.index - controller.previousIndex).abs();
if (tabsDelta != 0) {
progressLeft /= tabsDelta;
}
tabChangeProgress = 1 - clampDouble(progressLeft, 0.0, 1.0);
} else {
tabChangeProgress = (index - value).abs();
}
// If the animation has finished, there is no need to apply the stretch effect.
if (tabChangeProgress == 1.0) {
return rect;
}
final double leftFraction;
final double rightFraction;
final bool isMovingRight = switch (textDirection) {
TextDirection.ltr => controller.indexIsChanging ? index > value : value > index,
TextDirection.rtl => controller.indexIsChanging ? value > index : index > value,
};
if (isMovingRight) {
leftFraction = accelerateInterpolation(tabChangeProgress);
rightFraction = decelerateInterpolation(tabChangeProgress);
} else {
leftFraction = decelerateInterpolation(tabChangeProgress);
rightFraction = accelerateInterpolation(tabChangeProgress);
}
final double lerpRectLeft;
final double lerpRectRight;
// The controller.indexIsChanging is true when the Tab is pressed, instead of swipe to change tabs.
// If the tab is pressed then only lerp between fromRect and toRect.
if (controller.indexIsChanging) {
lerpRectLeft = lerpDouble(fromRect.left, toRect.left, leftFraction)!;
lerpRectRight = lerpDouble(fromRect.right, toRect.right, rightFraction)!;
} else {
// Switch the Rect left and right lerp order based on swipe direction.
lerpRectLeft = switch (isMovingRight) {
true => lerpDouble(fromRect.left, toRect.left, leftFraction)!,
false => lerpDouble(toRect.left, fromRect.left, leftFraction)!,
};
lerpRectRight = switch (isMovingRight) {
true => lerpDouble(fromRect.right, toRect.right, rightFraction)!,
false => lerpDouble(toRect.right, fromRect.right, rightFraction)!,
};
}
return Rect.fromLTRB(lerpRectLeft, rect.top, lerpRectRight, rect.bottom);
}
@override
bool shouldRepaint(_IndicatorPainter old) {
return _needsPaint ||
controller != old.controller ||
indicator != old.indicator ||
tabKeys.length != old.tabKeys.length ||
(!listEquals(_currentTabOffsets, old._currentTabOffsets)) ||
_currentTextDirection != old._currentTextDirection;
}
}
class _ChangeAnimation extends Animation<double> with AnimationWithParentMixin<double> {
_ChangeAnimation(this.controller);
final TabController controller;
@override
Animation<double> get parent => controller.animation!;
@override
void removeStatusListener(AnimationStatusListener listener) {
if (controller.animation != null) {
super.removeStatusListener(listener);
}
}
@override
void removeListener(VoidCallback listener) {
if (controller.animation != null) {
super.removeListener(listener);
}
}
@override
double get value => _indexChangeProgress(controller);
}
class _DragAnimation extends Animation<double> with AnimationWithParentMixin<double> {
_DragAnimation(this.controller, this.index);
final TabController controller;
final int index;
@override
Animation<double> get parent => controller.animation!;
@override
void removeStatusListener(AnimationStatusListener listener) {
if (controller.animation != null) {
super.removeStatusListener(listener);
}
}
@override
void removeListener(VoidCallback listener) {
if (controller.animation != null) {
super.removeListener(listener);
}
}
@override
double get value {
assert(!controller.indexIsChanging);
final double controllerMaxValue = (controller.length - 1).toDouble();
final double controllerValue = clampDouble(
controller.animation!.value,
0.0,
controllerMaxValue,
);
return clampDouble((controllerValue - index.toDouble()).abs(), 0.0, 1.0);
}
}
// This class, and TabBarScrollController, only exist to handle the case
// where a scrollable TabBar has a non-zero initialIndex. In that case we can
// only compute the scroll position's initial scroll offset (the "correct"
// pixels value) after the TabBar viewport width and scroll limits are known.
class _TabBarScrollPosition extends ScrollPositionWithSingleContext {
_TabBarScrollPosition({
required super.physics,
required super.context,
required super.oldPosition,
required this.tabBar,
}) : super(initialPixels: null);
final _TabBarState tabBar;
bool _viewportDimensionWasNonZero = false;
// The scroll position should be adjusted at least once.
bool _needsPixelsCorrection = true;
@override
bool applyContentDimensions(double minScrollExtent, double maxScrollExtent) {
var result = true;
if (!_viewportDimensionWasNonZero) {
_viewportDimensionWasNonZero = viewportDimension != 0.0;
}
// If the viewport never had a non-zero dimension, we just want to jump
// to the initial scroll position to avoid strange scrolling effects in
// release mode: the viewport temporarily may have a dimension of zero
// before the actual dimension is calculated. In that scenario, setting
// the actual dimension would cause a strange scroll effect without this
// guard because the super call below would start a ballistic scroll activity.
if (!_viewportDimensionWasNonZero || _needsPixelsCorrection) {
_needsPixelsCorrection = false;
correctPixels(
tabBar._initialScrollOffset(viewportDimension, minScrollExtent, maxScrollExtent),
);
result = false;
}
return super.applyContentDimensions(minScrollExtent, maxScrollExtent) && result;
}
void markNeedsPixelsCorrection() {
_needsPixelsCorrection = true;
}
}
/// The [ScrollController] for a [TabBar] widget.
final class TabBarScrollController extends ScrollController {
/// The state of the [TabBar] widget to which this controller is attached.
///
/// Is null if this controller is not attached to a [TabBar].
_TabBarState? _tabBarState;
/// Asserts that this controller is currently attached to a [TabBar]'s [State].
///
/// To invoke this function, wrap it in an assert: `assert(debugCheckHasTabBarState());`
///
/// Does nothing if asserts are disabled. Always returns true.
bool debugCheckHasTabBarState() {
assert(_tabBarState != null, 'This TabBarScrollController is not attached to any TabBar.');
return true;
}
@override
ScrollPosition createScrollPosition(
ScrollPhysics physics,
ScrollContext context,
ScrollPosition? oldPosition,
) {
assert(debugCheckHasTabBarState());
return _TabBarScrollPosition(
physics: physics,
context: context,
oldPosition: oldPosition,
tabBar: _tabBarState!,
);
}
@override
void dispose() {
_tabBarState = null;
super.dispose();
}
}
/// Signature for [TabBar] callbacks that report that an underlying value has
/// changed for a given [Tab] at `index`.
///
/// Used for [TabBar.onHover] and [TabBar.onFocusChange] callbacks The provided
/// `value` being true indicates focus has been gained, or a pointer has hovered
/// over the tab, with false indicated focus has been lost or the pointer has
/// exited hovering.
typedef TabValueChanged<T> = void Function(T value, int index);
/// A Material Design primary tab bar.
///
/// Primary tabs are placed at the top of the content pane under a top app bar.
/// They display the main content destinations.
///
/// Typically created as the [AppBar.bottom] part of an [AppBar] and in
/// conjunction with a [TabBarView].
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=POtoEH-5l40}
///
/// If a [TabController] is not provided, then a [DefaultTabController] ancestor
/// must be provided instead. The tab controller's [TabController.length] must
/// equal the length of the [tabs] list and the length of the
/// [TabBarView.children] list.
///
/// Requires one of its ancestors to be a [Material] widget.
///
/// Uses values from [TabBarThemeData] if it is set in the current context.
///
/// {@tool dartpad}
/// This sample shows the implementation of [TabBar] and [TabBarView] using a [DefaultTabController].
/// Each [Tab] corresponds to a child of the [TabBarView] in the order they are written.
///
/// ** See code in examples/api/lib/material/tabs/tab_bar.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// [TabBar] can also be implemented by using a [TabController] which provides more options
/// to control the behavior of the [TabBar] and [TabBarView]. This can be used instead of
/// a [DefaultTabController], demonstrated below.
///
/// ** See code in examples/api/lib/material/tabs/tab_bar.1.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This sample showcases nested Material 3 [TabBar]s. It consists of a primary
/// [TabBar] with nested a secondary [TabBar]. The primary [TabBar] uses a
/// [DefaultTabController] while the secondary [TabBar] uses a [TabController].
///
/// ** See code in examples/api/lib/material/tabs/tab_bar.2.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This sample showcases how to apply custom behavior based on the scroll in [TabBar].
/// It utilizes scroll notifications ([ScrollMetricsNotification]
/// and [ScrollNotification]) within [NotificationListener] callback
/// to monitor the scroll offset, allowing for interface customization
/// based on the obtained offset.
///
/// ** See code in examples/api/lib/material/tabs/tab_bar.3.dart **
/// {@end-tool}
///
/// See also:
///
/// * [TabBar.secondary], for a secondary tab bar.
/// * [TabBarView], which displays page views that correspond to each tab.
/// * [TabController], which coordinates tab selection between a [TabBar] and a [TabBarView].
/// * https://m3.material.io/components/tabs/overview, the Material 3
/// tab bar specification.
class TabBar extends StatefulWidget implements PreferredSizeWidget {
/// Creates a Material Design primary tab bar.
///
/// The length of the [tabs] argument must match the [controller]'s
/// [TabController.length].
///
/// If a [TabController] is not provided, then there must be a
/// [DefaultTabController] ancestor.
///
/// The [indicatorWeight] parameter defaults to 2.
///
/// The [indicatorPadding] parameter defaults to [EdgeInsets.zero].