-
Notifications
You must be signed in to change notification settings - Fork 30.1k
Expand file tree
/
Copy pathapp_bar.dart
More file actions
2620 lines (2393 loc) · 97.1 KB
/
app_bar.dart
File metadata and controls
2620 lines (2393 loc) · 97.1 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 'app.dart';
/// @docImport 'drawer.dart';
/// @docImport 'popup_menu.dart';
/// @docImport 'snack_bar.dart';
/// @docImport 'text_button.dart';
/// @docImport 'text_field.dart';
library;
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'action_buttons.dart';
import 'app_bar_theme.dart';
import 'button_style.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'constants.dart';
import 'debug.dart';
import 'flexible_space_bar.dart';
import 'icon_button.dart';
import 'icon_button_theme.dart';
import 'icons.dart';
import 'material.dart';
import 'scaffold.dart';
import 'tabs.dart';
import 'text_theme.dart';
import 'theme.dart';
// Examples can assume:
// late String _logoAsset;
// double _myToolbarHeight = 250.0;
typedef _FlexibleConfigBuilder = _ScrollUnderFlexibleConfig Function(BuildContext);
const double _kLeadingWidth = kToolbarHeight; // So the leading button is square.
const double _kMaxTitleTextScaleFactor =
1.34; // TODO(perc): Add link to Material spec when available, https://github.com/flutter/flutter/issues/58769.
enum _SliverAppVariant { small, medium, large }
// Bottom justify the toolbarHeight child which may overflow the top.
class _ToolbarContainerLayout extends SingleChildLayoutDelegate {
const _ToolbarContainerLayout(this.toolbarHeight);
final double toolbarHeight;
@override
BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
return constraints.tighten(height: toolbarHeight);
}
@override
Size getSize(BoxConstraints constraints) {
return Size(constraints.maxWidth, toolbarHeight);
}
@override
Offset getPositionForChild(Size size, Size childSize) {
return Offset(0.0, size.height - childSize.height);
}
@override
bool shouldRelayout(_ToolbarContainerLayout oldDelegate) =>
toolbarHeight != oldDelegate.toolbarHeight;
}
class _PreferredAppBarSize extends Size {
_PreferredAppBarSize(this.toolbarHeight, this.bottomHeight)
: super.fromHeight((toolbarHeight ?? kToolbarHeight) + (bottomHeight ?? 0));
final double? toolbarHeight;
final double? bottomHeight;
}
/// A Material Design app bar.
///
/// An app bar consists of a toolbar and potentially other widgets, such as a
/// [TabBar] and a [FlexibleSpaceBar]. App bars typically expose one or more
/// common [actions] with [IconButton]s which are optionally followed by a
/// [PopupMenuButton] for less common operations (sometimes called the "overflow
/// menu").
///
/// App bars are typically used in the [Scaffold.appBar] property, which places
/// the app bar as a fixed-height widget at the top of the screen. For a scrollable
/// app bar, see [SliverAppBar], which embeds an [AppBar] in a sliver for use in
/// a [CustomScrollView].
///
/// The AppBar displays the toolbar widgets, [leading], [title], and [actions],
/// above the [bottom] (if any). The [bottom] is usually used for a [TabBar]. If
/// a [flexibleSpace] widget is specified then it is stacked behind the toolbar
/// and the bottom widget. The following diagram shows where each of these slots
/// appears in the toolbar when the writing language is left-to-right (e.g.
/// English):
///
/// 
///
/// If the [leading] widget is omitted, but the [AppBar] is in a [Scaffold] with
/// a [Drawer], then a button will be inserted to open the drawer. Otherwise, if
/// the nearest [Navigator] has any previous routes, a [BackButton] is inserted
/// instead. This behavior can be turned off by setting the [automaticallyImplyLeading]
/// to false. In that case a null leading widget will result in the middle/title widget
/// stretching to start.
///
/// If the [actions] widget list is omitted or empty, but the [AppBar] is in a [Scaffold] with
/// an end [Drawer], then a button will be inserted to open the end drawer.
/// This behavior can be turned off by setting the [automaticallyImplyActions]
/// to false.
///
/// The [AppBar] insets its content based on the ambient [MediaQuery]'s padding,
/// to avoid system UI intrusions. It's taken care of by [Scaffold] when used in
/// the [Scaffold.appBar] property. When animating an [AppBar], unexpected
/// [MediaQuery] changes (as is common in [Hero] animations) may cause the content
/// to suddenly jump. Wrap the [AppBar] in a [MediaQuery] widget, and adjust its
/// padding such that the animation is smooth.
///
/// {@tool dartpad}
/// This sample shows an [AppBar] with two simple actions. The first action
/// opens a [SnackBar], while the second action navigates to a new page.
///
/// ** See code in examples/api/lib/material/app_bar/app_bar.0.dart **
/// {@end-tool}
///
/// Material Design 3 introduced new types of app bar.
/// {@tool dartpad}
/// This sample shows the creation of an [AppBar] widget with the [shadowColor] and
/// [scrolledUnderElevation] properties set, as described in:
/// https://m3.material.io/components/top-app-bar/overview
///
/// ** See code in examples/api/lib/material/app_bar/app_bar.1.dart **
/// {@end-tool}
///
/// ## Troubleshooting
///
/// ### Why don't my TextButton actions appear?
///
/// If the app bar's [actions] contains [TextButton]s, they will not
/// be visible if their foreground (text) color is the same as the
/// app bar's background color.
///
/// In Material v2 (i.e., when [ThemeData.useMaterial3] is false),
/// the default app bar [backgroundColor] is the overall theme's
/// [ColorScheme.primary] if the overall theme's brightness is
/// [Brightness.light]. Unfortunately this is the same as the default
/// [ButtonStyle.foregroundColor] for [TextButton] for light themes.
/// In this case a preferable text button foreground color is
/// [ColorScheme.onPrimary], a color that contrasts nicely with
/// [ColorScheme.primary]. To remedy the problem, override
/// [TextButton.style]:
///
/// {@tool dartpad}
/// This sample shows an [AppBar] with two action buttons with their primary
/// color set to [ColorScheme.onPrimary].
///
/// ** See code in examples/api/lib/material/app_bar/app_bar.2.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows how to listen to a nested Scrollable's scroll notification
/// in a nested scroll view using the [notificationPredicate] property and use it
/// to make [scrolledUnderElevation] take effect.
///
/// ** See code in examples/api/lib/material/app_bar/app_bar.3.dart **
/// {@end-tool}
///
/// See also:
///
/// * [Scaffold], which displays the [AppBar] in its [Scaffold.appBar] slot.
/// * [SliverAppBar], which uses [AppBar] to provide a flexible app bar that
/// can be used in a [CustomScrollView].
/// * [TabBar], which is typically placed in the [bottom] slot of the [AppBar]
/// if the screen has multiple pages arranged in tabs.
/// * [IconButton], which is used with [actions] to show buttons on the app bar.
/// * [PopupMenuButton], to show a popup menu on the app bar, via [actions].
/// * [FlexibleSpaceBar], which is used with [flexibleSpace] when the app bar
/// can expand and collapse.
/// * <https://material.io/design/components/app-bars-top.html>
/// * <https://m3.material.io/components/top-app-bar>
/// * Cookbook: [Place a floating app bar above a list](https://docs.flutter.dev/cookbook/lists/floating-app-bar)
class AppBar extends StatefulWidget implements PreferredSizeWidget {
/// Creates a Material Design app bar.
///
/// If [elevation] is specified, it must be non-negative.
///
/// Typically used in the [Scaffold.appBar] property.
AppBar({
super.key,
this.leading,
this.automaticallyImplyLeading = true,
this.title,
this.actions,
this.automaticallyImplyActions = true,
this.flexibleSpace,
this.bottom,
this.elevation,
this.scrolledUnderElevation,
this.notificationPredicate = defaultScrollNotificationPredicate,
this.shadowColor,
this.surfaceTintColor,
this.shape,
this.backgroundColor,
this.foregroundColor,
this.iconTheme,
this.actionsIconTheme,
this.primary = true,
this.centerTitle,
this.excludeHeaderSemantics = false,
this.titleSpacing,
this.toolbarOpacity = 1.0,
this.bottomOpacity = 1.0,
this.toolbarHeight,
this.leadingWidth,
this.toolbarTextStyle,
this.titleTextStyle,
this.systemOverlayStyle,
this.forceMaterialTransparency = false,
this.useDefaultSemanticsOrder = true,
this.clipBehavior,
this.actionsPadding,
this.animateColor = false,
}) : assert(elevation == null || elevation >= 0.0),
preferredSize = _PreferredAppBarSize(toolbarHeight, bottom?.preferredSize.height);
/// Used by [Scaffold] to compute its [AppBar]'s overall height. The returned value is
/// the same `preferredSize.height` unless [AppBar.toolbarHeight] was null and
/// `AppBarTheme.of(context).toolbarHeight` is non-null. In that case the
/// return value is the sum of the theme's toolbar height and the height of
/// the app bar's [AppBar.bottom] widget.
static double preferredHeightFor(BuildContext context, Size preferredSize) {
if (preferredSize is _PreferredAppBarSize && preferredSize.toolbarHeight == null) {
return (AppBarTheme.of(context).toolbarHeight ?? kToolbarHeight) +
(preferredSize.bottomHeight ?? 0);
}
return preferredSize.height;
}
/// {@template flutter.material.appbar.leading}
/// A widget to display before the toolbar's [title].
///
/// Typically the [leading] widget is an [Icon] or an [IconButton].
///
/// Becomes the leading component of the [NavigationToolbar] built
/// by this widget. The [leading] widget's width and height are constrained to
/// be no bigger than [leadingWidth] and [toolbarHeight] respectively.
///
/// If this is null and [automaticallyImplyLeading] is set to true, the
/// [AppBar] will imply an appropriate widget. For example, if the [AppBar] is
/// in a [Scaffold] that also has a [Drawer], the [Scaffold] will fill this
/// widget with an [IconButton] that opens the drawer (using [Icons.menu]). If
/// there's no [Drawer] and the parent [Navigator] can go back, the [AppBar]
/// will use a [BackButton] that calls [Navigator.maybePop].
/// {@endtemplate}
///
/// {@tool snippet}
///
/// The following code shows how the drawer button could be manually specified
/// instead of relying on [automaticallyImplyLeading]:
///
/// ```dart
/// AppBar(
/// leading: Builder(
/// builder: (BuildContext context) {
/// return IconButton(
/// icon: const Icon(Icons.menu),
/// onPressed: () { Scaffold.of(context).openDrawer(); },
/// tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
/// );
/// },
/// ),
/// )
/// ```
/// {@end-tool}
///
/// The [Builder] is used in this example to ensure that the `context` refers
/// to that part of the subtree. That way this code snippet can be used even
/// inside the very code that is creating the [Scaffold] (in which case,
/// without the [Builder], the `context` wouldn't be able to see the
/// [Scaffold], since it would refer to an ancestor of that widget).
///
/// See also:
///
/// * [Scaffold.appBar], in which an [AppBar] is usually placed.
/// * [Scaffold.drawer], in which the [Drawer] is usually placed.
final Widget? leading;
/// {@template flutter.material.appbar.automaticallyImplyLeading}
/// Controls whether we should try to imply the leading widget if null.
///
/// If true and [AppBar.leading] is null, automatically try to deduce what the leading
/// widget should be. If false and [AppBar.leading] is null, leading space is given to [AppBar.title].
/// If leading widget is not null, this parameter has no effect.
/// {@endtemplate}
final bool automaticallyImplyLeading;
/// {@template flutter.material.appbar.title}
/// The primary widget displayed in the app bar.
///
/// Becomes the middle component of the [NavigationToolbar] built by this widget.
///
/// Typically a [Text] widget that contains a description of the current
/// contents of the app.
/// {@endtemplate}
///
/// The [title]'s width is constrained to fit within the remaining space
/// between the toolbar's [leading] and [actions] widgets. Its height is
/// _not_ constrained. The [title] is vertically centered and clipped to fit
/// within the toolbar, whose height is [toolbarHeight]. Typically this
/// isn't noticeable because a simple [Text] [title] will fit within the
/// toolbar by default. On the other hand, it is noticeable when a
/// widget with an intrinsic height that is greater than [toolbarHeight]
/// is used as the [title]. For example, when the height of an Image used
/// as the [title] exceeds [toolbarHeight], it will be centered and
/// clipped (top and bottom), which may be undesirable. In cases like this
/// the height of the [title] widget can be constrained. For example:
///
/// ```dart
/// MaterialApp(
/// home: Scaffold(
/// appBar: AppBar(
/// title: SizedBox(
/// height: _myToolbarHeight,
/// child: Image.asset(_logoAsset),
/// ),
/// toolbarHeight: _myToolbarHeight,
/// ),
/// ),
/// )
/// ```
final Widget? title;
/// {@template flutter.material.appbar.actions}
/// A list of Widgets to display in a row after the [title] widget.
///
/// Typically these widgets are [IconButton]s representing common operations.
/// For less common operations, consider using a [PopupMenuButton] as the
/// last action.
///
/// The [actions] become the trailing component of the [NavigationToolbar] built
/// by this widget. The height of each action is constrained to be no bigger
/// than the [toolbarHeight].
///
/// To avoid having the last action covered by the debug banner, you may want
/// to set the [MaterialApp.debugShowCheckedModeBanner] to false.
///
/// If this is null or empty and [automaticallyImplyActions] is set to true, the
/// [AppBar] will imply an appropriate widget. For example, if the [AppBar] is
/// in a [Scaffold] that also has an end [Drawer], the [Scaffold] will fill this
/// widget with an [IconButton] that opens the end drawer (using [Icons.menu]).
/// {@endtemplate}
///
/// {@tool snippet}
///
/// ```dart
/// Scaffold(
/// body: CustomScrollView(
/// primary: true,
/// slivers: <Widget>[
/// SliverAppBar(
/// title: const Text('Hello World'),
/// actions: <Widget>[
/// IconButton(
/// icon: const Icon(Icons.shopping_cart),
/// tooltip: 'Open shopping cart',
/// onPressed: () {
/// // handle the press
/// },
/// ),
/// ],
/// ),
/// // ...rest of body...
/// ],
/// ),
/// )
/// ```
/// {@end-tool}
final List<Widget>? actions;
/// {@template flutter.material.appbar.automaticallyImplyActions}
/// Controls whether we should try to imply the actions widget if null.
///
/// If true and [AppBar.actions] is null or empty, automatically try to deduce what the actions
/// widget should be. If false and [AppBar.actions] is null or empty, the actions widget list is kept empty.
/// If [AppBar.actions] is not null, this parameter has no effect.
/// {@endtemplate}
final bool automaticallyImplyActions;
/// {@template flutter.material.appbar.flexibleSpace}
/// This widget is stacked behind the toolbar and the tab bar. Its height will
/// be the same as the app bar's overall height.
///
/// A flexible space isn't actually flexible unless the [AppBar]'s container
/// changes the [AppBar]'s size. A [SliverAppBar] in a [CustomScrollView]
/// changes the [AppBar]'s height when scrolled.
///
/// Typically a [FlexibleSpaceBar]. See [FlexibleSpaceBar] for details.
/// {@endtemplate}
final Widget? flexibleSpace;
/// {@template flutter.material.appbar.bottom}
/// This widget appears across the bottom of the app bar.
///
/// Typically a [TabBar]. Only widgets that implement [PreferredSizeWidget] can
/// be used at the bottom of an app bar.
/// {@endtemplate}
///
/// See also:
///
/// * [PreferredSize], which can be used to give an arbitrary widget a preferred size.
final PreferredSizeWidget? bottom;
/// {@template flutter.material.appbar.elevation}
/// The z-coordinate at which to place this app bar relative to its parent.
///
/// This property controls the size of the shadow below the app bar if
/// [shadowColor] is not null.
///
/// If [surfaceTintColor] is not null then it will apply a surface tint overlay
/// to the background color (see [Material.surfaceTintColor] for more
/// detail).
///
/// The value must be non-negative.
///
/// If this property is null, then the ambient [AppBarThemeData.elevation]
/// is used. If that is also null, the default value is 4.
/// {@endtemplate}
///
/// See also:
///
/// * [scrolledUnderElevation], which will be used when the app bar has
/// something scrolled underneath it.
/// * [shadowColor], which is the color of the shadow below the app bar.
/// * [surfaceTintColor], which determines the elevation overlay that will
/// be applied to the background of the app bar.
/// * [shape], which defines the shape of the app bar's [Material] and its
/// shadow.
final double? elevation;
/// {@template flutter.material.appbar.scrolledUnderElevation}
/// The elevation that will be used if this app bar has something
/// scrolled underneath it.
///
/// If this property is null, then the ambient [AppBarThemeData.scrolledUnderElevation]
/// is used. If that is also null then [elevation] is used.
///
/// The value must be non-negative.
///
/// {@endtemplate}
///
/// See also:
/// * [elevation], which will be used if there is no content scrolled under
/// the app bar.
/// * [shadowColor], which is the color of the shadow below the app bar.
/// * [surfaceTintColor], which determines the elevation overlay that will
/// be applied to the background of the app bar.
/// * [shape], which defines the shape of the app bar's [Material] and its
/// shadow.
final double? scrolledUnderElevation;
/// A check that specifies which child's [ScrollNotification]s should be
/// listened to.
///
/// By default, checks whether `notification.depth == 0`. Set it to something
/// else for more complicated layouts.
final ScrollNotificationPredicate notificationPredicate;
/// {@template flutter.material.appbar.shadowColor}
/// The color of the shadow below the app bar.
///
/// If this property is null, then the ambient [AppBarThemeData.shadowColor]
/// is used. If that is also null, the default value is fully opaque black.
/// {@endtemplate}
///
/// See also:
///
/// * [elevation], which defines the size of the shadow below the app bar.
/// * [shape], which defines the shape of the app bar and its shadow.
final Color? shadowColor;
/// {@template flutter.material.appbar.surfaceTintColor}
/// The color of the surface tint overlay applied to the app bar's
/// background color to indicate elevation.
///
/// If null no overlay will be applied.
/// {@endtemplate}
///
/// See also:
/// * [Material.surfaceTintColor], which described this feature in more detail.
final Color? surfaceTintColor;
/// {@template flutter.material.appbar.shape}
/// The shape of the app bar's [Material] as well as its shadow.
///
/// If this property is null, then the ambient [AppBarThemeData.shape]
/// is used. Both properties default to null.
/// If both properties are null then the shape of the app bar's [Material]
/// is just a simple rectangle.
///
/// A shadow is only displayed if the [elevation] is greater than
/// zero.
/// {@endtemplate}
///
/// {@tool dartpad}
/// This sample demonstrates how to implement a custom app bar shape for the
/// [shape] property.
///
/// ** See code in examples/api/lib/material/app_bar/app_bar.4.dart **
/// {@end-tool}
/// See also:
///
/// * [elevation], which defines the size of the shadow below the app bar.
/// * [shadowColor], which is the color of the shadow below the app bar.
final ShapeBorder? shape;
/// {@template flutter.material.appbar.backgroundColor}
/// The fill color to use for an app bar's [Material].
///
/// If null, then the [AppBarTheme.backgroundColor] is used. If that value is also
/// null:
/// In Material v2 (i.e., when [ThemeData.useMaterial3] is false),
/// then [AppBar] uses the overall theme's [ColorScheme.primary] if the
/// overall theme's brightness is [Brightness.light], and [ColorScheme.surface]
/// if the overall theme's brightness is [Brightness.dark].
/// In Material v3 (i.e., when [ThemeData.useMaterial3] is true),
/// then [AppBar] uses the overall theme's [ColorScheme.surface]
///
/// If this color is a [WidgetStateColor] it will be resolved against
/// [WidgetState.scrolledUnder] when the content of the app's
/// primary scrollable overlaps the app bar.
/// {@endtemplate}
///
/// See also:
///
/// * [foregroundColor], which specifies the color for icons and text within
/// the app bar.
/// * [Theme.of], which returns the current overall Material theme as
/// a [ThemeData].
/// * [ThemeData.colorScheme], the thirteen colors that most Material widget
/// default colors are based on.
/// * [ColorScheme.brightness], which indicates if the overall [Theme]
/// is light or dark.
final Color? backgroundColor;
/// {@template flutter.material.appbar.foregroundColor}
/// The default color for [Text] and [Icon]s within the app bar.
///
/// If null, then [AppBarTheme.foregroundColor] is used. If that
/// value is also null:
/// In Material v2 (i.e., when [ThemeData.useMaterial3] is false),
/// then [AppBar] uses the overall theme's [ColorScheme.onPrimary] if the
/// overall theme's brightness is [Brightness.light], and [ColorScheme.onSurface]
/// if the overall theme's brightness is [Brightness.dark].
/// In Material v3 (i.e., when [ThemeData.useMaterial3] is true),
/// then [AppBar] uses the overall theme's [ColorScheme.onSurface].
///
/// This color is used to configure [DefaultTextStyle] that contains
/// the toolbar's children, and the default [IconTheme] widgets that
/// are created if [iconTheme] and [actionsIconTheme] are null.
/// {@endtemplate}
///
/// See also:
///
/// * [backgroundColor], which specifies the app bar's background color.
/// * [Theme.of], which returns the current overall Material theme as
/// a [ThemeData].
/// * [ThemeData.colorScheme], the thirteen colors that most Material widget
/// default colors are based on.
/// * [ColorScheme.brightness], which indicates if the overall [Theme]
/// is light or dark.
final Color? foregroundColor;
/// {@template flutter.material.appbar.iconTheme}
/// The color, opacity, and size to use for toolbar icons.
///
/// If this property is null, then a copy of [ThemeData.iconTheme]
/// is used, with the [IconThemeData.color] set to the
/// app bar's [foregroundColor].
/// {@endtemplate}
///
/// See also:
///
/// * [actionsIconTheme], which defines the appearance of icons in
/// the [actions] list.
final IconThemeData? iconTheme;
/// {@template flutter.material.appbar.actionsIconTheme}
/// The color, opacity, and size to use for the icons that appear in the app
/// bar's [actions].
///
/// This property should only be used when the [actions] should be
/// themed differently than the icon that appears in the app bar's [leading]
/// widget.
///
/// If this property is null, then the ambient [AppBarThemeData.actionsIconTheme]
/// is used. If that is also null, then the value of [iconTheme] is used.
/// {@endtemplate}
///
/// See also:
///
/// * [iconTheme], which defines the appearance of all of the toolbar icons.
final IconThemeData? actionsIconTheme;
/// {@template flutter.material.appbar.primary}
/// Whether this app bar is being displayed at the top of the screen.
///
/// If true, the app bar's toolbar elements and [bottom] widget will be
/// padded on top by the height of the system status bar. The layout
/// of the [flexibleSpace] is not affected by the [primary] property.
/// {@endtemplate}
final bool primary;
/// {@template flutter.material.appbar.centerTitle}
/// Whether the title should be centered.
///
/// If this property is null, then [AppBarTheme.centerTitle] of
/// [ThemeData.appBarTheme] is used. If that is also null, then value is
/// adapted to the current [TargetPlatform].
/// {@endtemplate}
final bool? centerTitle;
/// {@template flutter.material.appbar.excludeHeaderSemantics}
/// Whether the title should be wrapped with header [Semantics].
///
/// If false, the title will be used as [SemanticsProperties.namesRoute]
/// for Android, Fuchsia, Linux, and Windows platform. This means the title is
/// announced by screen reader when transition to this route.
///
/// The accessibility behavior is platform adaptive, based on the device's
/// actual platform rather than the theme's platform setting. This ensures that
/// assistive technologies like VoiceOver on iOS and macOS receive the correct
/// `namesRoute` semantic information, even when the app's theme is configured
/// to mimic a different platform's appearance.
///
/// Defaults to false.
/// {@endtemplate}
final bool excludeHeaderSemantics;
/// {@template flutter.material.appbar.titleSpacing}
/// The spacing around [title] content on the horizontal axis. This spacing is
/// applied even if there is no [leading] content or [actions]. If you want
/// [title] to take all the space available, set this value to 0.0.
///
/// If this property is null, then [AppBarTheme.titleSpacing] of
/// [ThemeData.appBarTheme] is used. If that is also null, then the
/// default value is [NavigationToolbar.kMiddleSpacing].
/// {@endtemplate}
final double? titleSpacing;
/// {@template flutter.material.appbar.toolbarOpacity}
/// How opaque the toolbar part of the app bar is.
///
/// A value of 1.0 is fully opaque, and a value of 0.0 is fully transparent.
///
/// Typically, this value is not changed from its default value (1.0). It is
/// used by [SliverAppBar] to animate the opacity of the toolbar when the app
/// bar is scrolled.
/// {@endtemplate}
final double toolbarOpacity;
/// {@template flutter.material.appbar.bottomOpacity}
/// How opaque the bottom part of the app bar is.
///
/// A value of 1.0 is fully opaque, and a value of 0.0 is fully transparent.
///
/// Typically, this value is not changed from its default value (1.0). It is
/// used by [SliverAppBar] to animate the opacity of the toolbar when the app
/// bar is scrolled.
/// {@endtemplate}
final double bottomOpacity;
/// {@template flutter.material.appbar.preferredSize}
/// A size whose height is the sum of [toolbarHeight] and the [bottom] widget's
/// preferred height.
///
/// [Scaffold] uses this size to set its app bar's height.
/// {@endtemplate}
@override
final Size preferredSize;
/// {@template flutter.material.appbar.toolbarHeight}
/// Defines the height of the toolbar component of an [AppBar].
///
/// By default, the value of [toolbarHeight] is [kToolbarHeight].
/// {@endtemplate}
final double? toolbarHeight;
/// {@template flutter.material.appbar.leadingWidth}
/// Defines the width of [AppBar.leading] widget.
///
/// By default, the value of [AppBar.leadingWidth] is 56.0.
/// {@endtemplate}
final double? leadingWidth;
/// {@template flutter.material.appbar.toolbarTextStyle}
/// The default text style for the AppBar's [leading], and
/// [actions] widgets, but not its [title].
///
/// If this property is null, then [AppBarTheme.toolbarTextStyle] of
/// [ThemeData.appBarTheme] is used. If that is also null, the default
/// value is a copy of the overall theme's [TextTheme.bodyMedium]
/// [TextStyle], with color set to the app bar's [foregroundColor].
/// {@endtemplate}
///
/// See also:
///
/// * [titleTextStyle], which overrides the default text style for the [title].
/// * [DefaultTextStyle], which overrides the default text style for all of the
/// widgets in a subtree.
final TextStyle? toolbarTextStyle;
/// {@template flutter.material.appbar.titleTextStyle}
/// The default text style for the AppBar's [title] widget.
///
/// If this property is null, then [AppBarTheme.titleTextStyle] of
/// [ThemeData.appBarTheme] is used. If that is also null, the default
/// value is a copy of the overall theme's [TextTheme.titleLarge]
/// [TextStyle], with color set to the app bar's [foregroundColor].
/// {@endtemplate}
///
/// See also:
///
/// * [toolbarTextStyle], which is the default text style for the AppBar's
/// [title], [leading], and [actions] widgets, also known as the
/// AppBar's "toolbar".
/// * [DefaultTextStyle], which overrides the default text style for all of the
/// widgets in a subtree.
final TextStyle? titleTextStyle;
/// {@template flutter.material.appbar.systemOverlayStyle}
/// Specifies the style to use for the system overlays (e.g. the status bar on
/// Android or iOS, the system navigation bar on Android).
///
/// If this property is null, then [AppBarTheme.systemOverlayStyle] of
/// [ThemeData.appBarTheme] is used. If that is also null, an appropriate
/// [SystemUiOverlayStyle] is calculated based on the [backgroundColor].
///
/// The AppBar's descendants are built within a
/// `AnnotatedRegion<SystemUiOverlayStyle>` widget, which causes
/// [SystemChrome.setSystemUIOverlayStyle] to be called
/// automatically. Apps should not enclose an AppBar with their
/// own [AnnotatedRegion].
/// {@endtemplate}
//
/// See also:
///
/// * [AnnotatedRegion], for placing [SystemUiOverlayStyle] in the layer tree.
/// * [SystemChrome.setSystemUIOverlayStyle], the imperative API for setting
/// system overlays style.
final SystemUiOverlayStyle? systemOverlayStyle;
/// {@template flutter.material.appbar.forceMaterialTransparency}
/// Forces the AppBar's Material widget type to be [MaterialType.transparency]
/// (instead of Material's default type).
///
/// This will remove the visual display of [backgroundColor] and [elevation],
/// and affect other characteristics of the AppBar's Material widget.
///
/// Provided for cases where the app bar is to be transparent, and gestures
/// must pass through the app bar to widgets beneath the app bar (i.e. with
/// [Scaffold.extendBodyBehindAppBar] set to true).
///
/// Defaults to false.
/// {@endtemplate}
final bool forceMaterialTransparency;
/// {@template flutter.material.appbar.useDefaultSemanticsOrder}
/// Whether to use the default semantic ordering for the app bar's children for
/// accessibility traversal order.
///
/// If this is set to true, the app bar will use the default semantic ordering,
/// which places the flexible space after the main content in the semantics tree.
/// This affects how screen readers and other assistive technologies navigate the app bar's content.
///
/// Set this to false if you want to customize semantics traversal order in the app bar.
/// You can then assign [SemanticsSortKey]s to app bar's children to control the order.
///
/// Defaults to true.
///
/// See also:
/// * [SemanticsSortKey], which are keys used to define the accessibility traversal order.
/// {@endtemplate}
final bool useDefaultSemanticsOrder;
/// {@macro flutter.material.Material.clipBehavior}
final Clip? clipBehavior;
/// {@template flutter.material.appbar.actionsPadding}
/// The padding between the [actions] and the end of the AppBar.
///
/// Defaults to zero.
/// {@endtemplate}
final EdgeInsetsGeometry? actionsPadding;
/// Whether the color should be animated.
final bool animateColor;
bool _getEffectiveCenterTitle(ThemeData theme, AppBarThemeData appbarTheme) {
bool platformCenter() {
return switch (theme.platform) {
TargetPlatform.iOS || TargetPlatform.macOS => actions == null || actions!.length < 2,
TargetPlatform.android ||
TargetPlatform.fuchsia ||
TargetPlatform.linux ||
TargetPlatform.windows => false,
};
}
return centerTitle ?? appbarTheme.centerTitle ?? platformCenter();
}
@override
State<AppBar> createState() => _AppBarState();
}
class _AppBarState extends State<AppBar> {
ScrollNotificationObserverState? _scrollNotificationObserver;
bool _scrolledUnder = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_scrollNotificationObserver?.removeListener(_handleScrollNotification);
final ScaffoldState? scaffoldState = Scaffold.maybeOf(context);
if (scaffoldState != null && (scaffoldState.isDrawerOpen || scaffoldState.isEndDrawerOpen)) {
return;
}
_scrollNotificationObserver = ScrollNotificationObserver.maybeOf(context);
_scrollNotificationObserver?.addListener(_handleScrollNotification);
}
@override
void dispose() {
if (_scrollNotificationObserver != null) {
_scrollNotificationObserver!.removeListener(_handleScrollNotification);
_scrollNotificationObserver = null;
}
super.dispose();
}
void _handleScrollNotification(ScrollNotification notification) {
if (notification is ScrollUpdateNotification && widget.notificationPredicate(notification)) {
final bool oldScrolledUnder = _scrolledUnder;
final ScrollMetrics metrics = notification.metrics;
switch (metrics.axisDirection) {
case AxisDirection.up:
// Scroll view is reversed
_scrolledUnder = metrics.extentAfter > 0;
case AxisDirection.down:
_scrolledUnder = metrics.extentBefore > 0;
case AxisDirection.right:
case AxisDirection.left:
// Scrolled under is only supported in the vertical axis, and should
// not be altered based on horizontal notifications of the same
// predicate since it could be a 2D scroller.
break;
}
if (_scrolledUnder != oldScrolledUnder) {
setState(() {
// React to a change in WidgetState.scrolledUnder
});
}
}
}
Color _resolveColor(
Set<WidgetState> states,
Color? widgetColor,
Color? themeColor,
Color defaultColor,
) {
return WidgetStateProperty.resolveAs<Color?>(widgetColor, states) ??
WidgetStateProperty.resolveAs<Color?>(themeColor, states) ??
WidgetStateProperty.resolveAs<Color>(defaultColor, states);
}
SystemUiOverlayStyle _systemOverlayStyleForBrightness(
Brightness brightness, [
Color? backgroundColor,
]) {
final SystemUiOverlayStyle style = brightness == Brightness.dark
? SystemUiOverlayStyle.light
: SystemUiOverlayStyle.dark;
// For backward compatibility, create an overlay style without system navigation bar settings.
return SystemUiOverlayStyle(
statusBarColor: backgroundColor,
statusBarBrightness: style.statusBarBrightness,
statusBarIconBrightness: style.statusBarIconBrightness,
systemStatusBarContrastEnforced: style.systemStatusBarContrastEnforced,
);
}
@override
Widget build(BuildContext context) {
assert(!widget.primary || debugCheckHasMediaQuery(context));
assert(debugCheckHasMaterialLocalizations(context));
final ThemeData theme = Theme.of(context);
final IconButtonThemeData iconButtonTheme = IconButtonTheme.of(context);
final AppBarThemeData appBarTheme = AppBarTheme.of(context);
final AppBarThemeData defaults = theme.useMaterial3
? _AppBarDefaultsM3(context)
: _AppBarDefaultsM2(context);
final ScaffoldState? scaffold = Scaffold.maybeOf(context);
final ModalRoute<dynamic>? parentRoute = ModalRoute.of(context);
final FlexibleSpaceBarSettings? settings = context
.dependOnInheritedWidgetOfExactType<FlexibleSpaceBarSettings>();
final states = <WidgetState>{
if (settings?.isScrolledUnder ?? _scrolledUnder) WidgetState.scrolledUnder,
};
final bool hasDrawer = scaffold?.hasDrawer ?? false;
final bool hasEndDrawer = scaffold?.hasEndDrawer ?? false;
final bool useCloseButton = parentRoute?.fullscreenDialog ?? false;
final double toolbarHeight =
widget.toolbarHeight ?? appBarTheme.toolbarHeight ?? kToolbarHeight;
final Color backgroundColor = _resolveColor(
states,
widget.backgroundColor,
appBarTheme.backgroundColor,
defaults.backgroundColor!,
);
final Color scrolledUnderBackground = _resolveColor(
states,
widget.backgroundColor,
appBarTheme.backgroundColor,
Theme.of(context).colorScheme.surfaceContainer,
);
final effectiveBackgroundColor = states.contains(WidgetState.scrolledUnder)
? scrolledUnderBackground
: backgroundColor;
final Color foregroundColor =
widget.foregroundColor ?? appBarTheme.foregroundColor ?? defaults.foregroundColor!;
final double elevation = widget.elevation ?? appBarTheme.elevation ?? defaults.elevation!;
final double effectiveElevation = states.contains(WidgetState.scrolledUnder)
? widget.scrolledUnderElevation ??
appBarTheme.scrolledUnderElevation ??
defaults.scrolledUnderElevation ??
elevation
: elevation;
IconThemeData overallIconTheme =
widget.iconTheme ??
appBarTheme.iconTheme ??
defaults.iconTheme!.copyWith(color: foregroundColor);
final Color? actionForegroundColor = widget.foregroundColor ?? appBarTheme.foregroundColor;
IconThemeData actionsIconTheme =
widget.actionsIconTheme ??
appBarTheme.actionsIconTheme ??
widget.iconTheme ??
appBarTheme.iconTheme ??
defaults.actionsIconTheme?.copyWith(color: actionForegroundColor) ??
overallIconTheme;
final EdgeInsetsGeometry actionsPadding =
widget.actionsPadding ?? appBarTheme.actionsPadding ?? defaults.actionsPadding!;
TextStyle? toolbarTextStyle =
widget.toolbarTextStyle ??
appBarTheme.toolbarTextStyle ??
defaults.toolbarTextStyle?.copyWith(color: foregroundColor);
TextStyle? titleTextStyle =
widget.titleTextStyle ??
appBarTheme.titleTextStyle ??
defaults.titleTextStyle?.copyWith(color: foregroundColor);
if (widget.toolbarOpacity != 1.0) {
final double opacity = const Interval(
0.25,
1.0,
curve: Curves.fastOutSlowIn,
).transform(widget.toolbarOpacity);
if (titleTextStyle?.color != null) {
titleTextStyle = titleTextStyle!.copyWith(
color: titleTextStyle.color!.withOpacity(opacity),
);
}
if (toolbarTextStyle?.color != null) {
toolbarTextStyle = toolbarTextStyle!.copyWith(
color: toolbarTextStyle.color!.withOpacity(opacity),
);
}