-
Notifications
You must be signed in to change notification settings - Fork 30.5k
Expand file tree
/
Copy pathnav_bar.dart
More file actions
3548 lines (3181 loc) · 128 KB
/
nav_bar.dart
File metadata and controls
3548 lines (3181 loc) · 128 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 'refresh.dart';
library;
import 'dart:math' as math;
import 'dart:ui' show ImageFilter;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'button.dart';
import 'colors.dart';
import 'constants.dart';
import 'icons.dart';
import 'localizations.dart';
import 'page_scaffold.dart';
import 'route.dart';
import 'search_field.dart';
import 'sheet.dart';
import 'theme.dart';
/// Modes that determine how to display the navigation bar's bottom in relation to scroll events.
enum NavigationBarBottomMode {
/// Enable hiding the bottom in response to scrolling.
///
/// As scrolling starts, the large title stays pinned while the bottom resizes
/// until it is completely consumed. Then, the large title scrolls under the
/// persistent navigation bar.
automatic,
/// Always display the bottom regardless of the scroll activity.
///
/// When scrolled, the bottom stays pinned while the large title scrolls under
/// the persistent navigation bar.
always,
}
/// Standard iOS navigation bar height without the status bar.
///
/// This height is constant and independent of accessibility as it is in iOS.
const double _kNavBarPersistentHeight = kMinInteractiveDimensionCupertino;
/// Size increase from expanding the navigation bar into an iOS-11-style large title
/// configuration in a [CustomScrollView].
const double _kNavBarLargeTitleHeightExtension = 52.0;
/// Number of logical pixels scrolled down before the title text is transferred
/// from the normal navigation bar to a big title below the navigation bar.
const double _kNavBarShowLargeTitleThreshold = 10.0;
/// Number of logical pixels scrolled during which the navigation bar's background
/// fades in or out.
///
/// Eyeballed on the native Settings app on an iPhone 15 simulator running iOS 17.4.
const double _kNavBarScrollUnderAnimationExtent = 10.0;
const double _kNavBarEdgePadding = 16.0;
const double _kNavBarBottomPadding = 8.0;
const double _kNavBarBackButtonTapWidth = 50.0;
// The minimum text scale to apply to contents of the nav bar which can scale to
// a size less than the default, such as the large title.
//
// Eyeballed on an iPhone 15 simulator running iOS 17.5.
const double _kMinScaleFactor = 0.9;
// The maximum text scale to apply to contents of the nav bar, except the large
// title which can grow larger but is damped.
//
// Calculated on an iPhone 15 simulator running iOS 17.5.
const double _kMaxScaleFactor = 1.235;
// The damping ratio applied to reduce the rate at which the large title scales.
//
// Eyeballed on an iPhone 15 simulator running iOS 17.5.
const double _kLargeTitleScaleDampingRatio = 3.0;
/// The width of the 'Cancel' button if the search field in a
/// [CupertinoSliverNavigationBar.search] is active.
///
/// Eyeballed on an iPhone 15 simulator running iOS 17.5.
const double _kSearchFieldCancelButtonWidth = 67.0;
/// The height of the unscaled search field used in
/// a [CupertinoSliverNavigationBar.search].
const double _kSearchFieldHeight = 36.0;
/// The duration of the animation when the search field in
/// [CupertinoSliverNavigationBar.search] is tapped.
const Duration _kNavBarSearchDuration = Duration(milliseconds: 300);
/// The curve of the animation when the search field in
/// [CupertinoSliverNavigationBar.search] is tapped.
const Curve _kNavBarSearchCurve = Curves.easeInOut;
/// Title text transfer fade.
const Duration _kNavBarTitleFadeDuration = Duration(milliseconds: 150);
const Color _kDefaultNavBarBorderColor = Color(0x4D000000);
const Border _kDefaultNavBarBorder = Border(
bottom: BorderSide(
color: _kDefaultNavBarBorderColor,
width: 0.0, // 0.0 means one physical pixel
),
);
const Border _kTransparentNavBarBorder = Border(
bottom: BorderSide(color: Color(0x00000000), width: 0.0),
);
/// The curve of the animation of the top nav bar regardless of push/pop
/// direction in the hero transition between two nav bars.
///
/// Eyeballed on an iPhone 15 Pro simulator running iOS 17.5.
const Curve _kTopNavBarHeaderTransitionCurve = Cubic(0.0, 0.45, 0.45, 0.98);
/// The curve of the animation of the bottom nav bar regardless of push/pop
/// direction in the hero transition between two nav bars.
///
/// Eyeballed on an iPhone 15 Pro simulator running iOS 17.5.
const Curve _kBottomNavBarHeaderTransitionCurve = Cubic(0.05, 0.90, 0.90, 0.95);
// There's a single tag for all instances of navigation bars because they can
// all transition between each other (per Navigator) via Hero transitions.
const _HeroTag _defaultHeroTag = _HeroTag(null);
@immutable
class _HeroTag {
const _HeroTag(this.navigator);
final NavigatorState? navigator;
// Let the Hero tag be described in tree dumps.
@override
String toString() => 'Default Hero tag for Cupertino navigation bars with navigator $navigator';
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is _HeroTag && other.navigator == navigator;
}
@override
int get hashCode => identityHashCode(navigator);
}
// An `AnimatedWidget` that imposes a fixed size on its child widget, and
// shifts the child widget in the parent stack, driven by its `offsetAnimation`
// property.
class _FixedSizeSlidingTransition extends AnimatedWidget {
const _FixedSizeSlidingTransition({
required this.isLTR,
required this.offsetAnimation,
required this.width,
required this.height,
required this.child,
}) : super(listenable: offsetAnimation);
// Whether the writing direction used in the navigation bar transition is
// left-to-right.
final bool isLTR;
// The fixed width to impose on `child`.
final double width;
// The fixed height to impose on `child`.
final double height;
// The animated offset from the top-leading corner of the stack.
//
// When `isLTR` is true, the `Offset` is the position of the child widget in
// the stack render box's regular coordinate space.
//
// When `isLTR` is false, the coordinate system is flipped around the
// horizontal axis and the origin is set to the top right corner of the render
// boxes. In other words, this parameter describes the offset from the top
// right corner of the stack, to the top right corner of the child widget, and
// the x-axis runs right to left.
final Animation<Offset> offsetAnimation;
final Widget child;
@override
Widget build(BuildContext context) {
return Positioned(
top: offsetAnimation.value.dy,
left: isLTR ? offsetAnimation.value.dx : null,
right: isLTR ? null : offsetAnimation.value.dx,
width: width,
height: height,
child: child,
);
}
}
/// Returns `child` wrapped with background and a bottom border if background color
/// is opaque. Otherwise, also blur with [BackdropFilter].
///
/// When `updateSystemUiOverlay` is true, the nav bar will update the OS
/// status bar's color theme based on the background color of the nav bar.
Widget _wrapWithBackground({
Border? border,
required Color backgroundColor,
Brightness? brightness,
required Widget child,
bool updateSystemUiOverlay = true,
bool enableBackgroundFilterBlur = true,
}) {
var result = child;
if (updateSystemUiOverlay) {
final bool isDark = backgroundColor.computeLuminance() < 0.179;
final Brightness newBrightness = brightness ?? (isDark ? Brightness.dark : Brightness.light);
final SystemUiOverlayStyle overlayStyle = switch (newBrightness) {
Brightness.dark => SystemUiOverlayStyle.light,
Brightness.light => SystemUiOverlayStyle.dark,
};
// [SystemUiOverlayStyle.light] and [SystemUiOverlayStyle.dark] set some system
// navigation bar properties,
// Before https://github.com/flutter/flutter/pull/104827 those properties
// had no effect, now they are used if there is no AnnotatedRegion on the
// bottom of the screen.
// For backward compatibility, create a `SystemUiOverlayStyle` without the
// system navigation bar properties.
result = AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: overlayStyle.statusBarColor,
statusBarBrightness: overlayStyle.statusBarBrightness,
statusBarIconBrightness: overlayStyle.statusBarIconBrightness,
systemStatusBarContrastEnforced: overlayStyle.systemStatusBarContrastEnforced,
),
child: result,
);
}
final childWithBackground = DecoratedBox(
decoration: BoxDecoration(border: border, color: backgroundColor),
child: result,
);
return ClipRect(
child: BackdropFilter(
enabled: backgroundColor.alpha != 0xFF && enableBackgroundFilterBlur,
filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
child: childWithBackground,
),
);
}
double _dampScaleFactor(double scaledFontSize, double unscaledFontSize, double dampingRatio) {
final double scaleFactor = scaledFontSize / unscaledFontSize;
return scaleFactor < 1.0
? math.max(_kMinScaleFactor, scaleFactor)
: 1.0 + ((scaleFactor - 1.0) / dampingRatio);
}
// Whether the current route supports nav bar hero transitions from or to.
bool _isTransitionable(BuildContext context) {
final ModalRoute<dynamic>? route = ModalRoute.of(context);
// Fullscreen dialogs never transitions their nav bar with other push-style
// pages' nav bars or with other fullscreen dialog pages on the way in or on
// the way out.
return route is PageRoute &&
!route.fullscreenDialog &&
!CupertinoSheetRoute.hasParentSheet(context);
}
/// An iOS-styled navigation bar.
///
/// The navigation bar is a toolbar that minimally consists of a widget,
/// normally a page title.
///
/// It also supports [leading] and [trailing] widgets on either end of the
/// toolbar, typically for actions and navigation.
///
/// The [leading] widget will automatically be a back chevron icon button (or a
/// cancel button in case of a fullscreen dialog) to pop the current route if none
/// is provided and [automaticallyImplyLeading] is true (true by default).
///
/// This toolbar should be placed at top of the screen where it will
/// automatically account for the OS's status bar.
///
/// If the given [backgroundColor]'s opacity is not 1.0 (which is the case by
/// default), it will produce a blurring effect to the content behind it.
///
/// ### Layout options
///
/// While the [CupertinoSliverNavigationBar] can dynamically change size and
/// layout in response to scrolling, this static version can reflect the same
/// large (expanded) layout, or the small (collapsed) layout.
///
/// The default constructor will display the collapsed version of the
/// [CupertinoSliverNavigationBar]. The [middle] widget will automatically be a
/// title text from the current [CupertinoPageRoute] if none is provided and
/// [automaticallyImplyMiddle] is true (true by default).
///
/// Using the [CupertinoNavigationBar.large] constructor will display the
/// expanded version of [CupertinoSliverNavigationBar]. The [largeTitle] widget
/// will automatically be a title text from the current [CupertinoPageRoute] if
/// none is provided and `automaticallyImplyTitle` is true (true by default).
///
/// ### Transitions
///
/// When [transitionBetweenRoutes] is true, this navigation bar will transition
/// on top of the routes instead of inside them if the route being transitioned
/// to also has a [CupertinoNavigationBar] or a [CupertinoSliverNavigationBar]
/// with [transitionBetweenRoutes] set to true. If [transitionBetweenRoutes] is
/// true, none of the [Widget] parameters can contain a key in its subtree since
/// that widget will exist in multiple places in the tree simultaneously.
///
/// By default, only one [CupertinoNavigationBar] or [CupertinoSliverNavigationBar]
/// should be present in each [PageRoute] to support the default transitions.
/// Use [transitionBetweenRoutes] or [heroTag] to customize the transition
/// behavior for multiple navigation bars per route.
///
/// When used in a [CupertinoPageScaffold], [CupertinoPageScaffold.navigationBar]
/// disables text scaling to match the native iOS behavior. To override
/// this behavior, wrap each of the `navigationBar`'s components inside a
/// [MediaQuery] with the desired [TextScaler].
///
/// {@tool dartpad}
/// This example shows a [CupertinoNavigationBar] placed in a [CupertinoPageScaffold].
/// Since [backgroundColor]'s opacity is not 1.0, there is a blur effect and
/// content slides underneath.
///
/// ** See code in examples/api/lib/cupertino/nav_bar/cupertino_navigation_bar.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows the resulting layout from [CupertinoNavigationBar.large]
/// constructor, showing a large title similar to the expanded state of
/// [CupertinoSliverNavigationBar].
///
/// ** See code in examples/api/lib/cupertino/nav_bar/cupertino_navigation_bar.2.dart **
/// {@end-tool}
///
/// See also:
///
/// * [CupertinoPageScaffold], a page layout helper typically hosting the
/// [CupertinoNavigationBar].
/// * [CupertinoSliverNavigationBar] for a navigation bar to be placed in a
/// scrolling list and that supports iOS-11-style large titles.
/// * <https://developer.apple.com/design/human-interface-guidelines/ios/bars/navigation-bars/>
class CupertinoNavigationBar extends StatefulWidget implements ObstructingPreferredSizeWidget {
/// Creates a static iOS style navigation bar, with a centered [middle] title.
///
/// Similar to the collapsed state of [CupertinoSliverNavigationBar], which
/// can dynamically change size in response to scrolling.
///
/// See also:
///
/// * [CupertinoNavigationBar.large], which creates a static iOS style
/// navigation bar with a [largeTitle], similar to the expanded state of
/// [CupertinoSliverNavigationBar].
const CupertinoNavigationBar({
super.key,
this.leading,
this.automaticallyImplyLeading = true,
this.automaticallyImplyMiddle = true,
this.previousPageTitle,
this.middle,
this.trailing,
this.border = _kDefaultNavBarBorder,
this.backgroundColor,
this.automaticBackgroundVisibility = true,
this.enableBackgroundFilterBlur = true,
this.brightness,
this.padding,
this.transitionBetweenRoutes = true,
this.heroTag = _defaultHeroTag,
this.bottom,
}) : largeTitle = null,
assert(
!transitionBetweenRoutes || identical(heroTag, _defaultHeroTag),
'Cannot specify a heroTag override if this navigation bar does not '
'transition due to transitionBetweenRoutes = false.',
);
/// Creates a static iOS style navigation bar, with a left aligned [largeTitle].
///
/// Similar to the expanded state of [CupertinoSliverNavigationBar], which
/// can dynamically change size in response to scrolling.
///
/// See also:
///
/// * [CupertinoNavigationBar]'s base constructor, which creates a static
/// iOS style navigation bar with [middle], similar to the collapsed state
/// of [CupertinoSliverNavigationBar].
const CupertinoNavigationBar.large({
super.key,
this.largeTitle,
this.leading,
this.automaticallyImplyLeading = true,
bool automaticallyImplyTitle = true,
this.previousPageTitle,
this.trailing,
this.border = _kDefaultNavBarBorder,
this.backgroundColor,
this.automaticBackgroundVisibility = true,
this.enableBackgroundFilterBlur = true,
this.brightness,
this.padding,
this.transitionBetweenRoutes = true,
this.heroTag = _defaultHeroTag,
this.bottom,
}) : middle = null,
automaticallyImplyMiddle = automaticallyImplyTitle,
assert(
!transitionBetweenRoutes || identical(heroTag, _defaultHeroTag),
'Cannot specify a heroTag override if this navigation bar does not '
'transition due to transitionBetweenRoutes = false.',
);
/// The navigation bar's title, when using [CupertinoNavigationBar.large].
///
/// If null and `automaticallyImplyTitle` is true, an appropriate [Text]
/// title will be created if the current route is a [CupertinoPageRoute] and
/// has a `title`.
///
/// This property is null for the base [CupertinoNavigationBar] constructor,
/// which shows a collapsed navigation bar and uses [middle] for the title
/// instead.
///
/// See also:
///
/// * [CupertinoSliverNavigationBar.largeTitle], a similar property
/// in the expanded state of [CupertinoSliverNavigationBar], which can
/// dynamically change size in response to scrolling.
final Widget? largeTitle;
/// {@template flutter.cupertino.CupertinoNavigationBar.leading}
/// Widget to place at the start of the navigation bar. Normally a back button
/// for a normal page or a cancel button for full page dialogs.
///
/// If null and [automaticallyImplyLeading] is true, an appropriate button
/// will be automatically created.
/// {@endtemplate}
final Widget? leading;
/// {@template flutter.cupertino.CupertinoNavigationBar.automaticallyImplyLeading}
/// Controls whether we should try to imply the leading widget if null.
///
/// If true and [leading] is null, automatically try to deduce what the [leading]
/// widget should be. If [leading] widget is not null, this parameter has no effect.
///
/// Specifically this navigation bar will:
///
/// 1. Show a 'Cancel' button if the current route is a `fullscreenDialog`.
/// 2. Show a back chevron with [previousPageTitle] if [previousPageTitle] is
/// not null.
/// 3. Show a back chevron with the previous route's `title` if the current
/// route is a [CupertinoPageRoute] and the previous route is also a
/// [CupertinoPageRoute].
/// {@endtemplate}
final bool automaticallyImplyLeading;
/// Controls whether we should try to imply the middle widget if null.
///
/// If true and [middle] is null, automatically fill in a [Text] widget with
/// the current route's `title` if the route is a [CupertinoPageRoute].
/// If [middle] widget is not null, this parameter has no effect.
final bool automaticallyImplyMiddle;
/// {@template flutter.cupertino.CupertinoNavigationBar.previousPageTitle}
/// Manually specify the previous route's title when automatically implying
/// the leading back button.
///
/// Overrides the text shown with the back chevron instead of automatically
/// showing the previous [CupertinoPageRoute]'s `title` when
/// [automaticallyImplyLeading] is true.
///
/// Has no effect when [leading] is not null or if [automaticallyImplyLeading]
/// is false.
/// {@endtemplate}
final String? previousPageTitle;
/// The navigation bar's default title.
///
/// If null and [automaticallyImplyMiddle] is true, an appropriate [Text]
/// title will be created if the current route is a [CupertinoPageRoute] and
/// has a `title`.
///
/// This property is null for the [CupertinoNavigationBar.large] constructor,
/// which shows an expanded navigation bar and uses [largeTitle] instead.
///
/// See also:
///
/// * [CupertinoSliverNavigationBar.middle], a similar property
/// in the collapsed state of [CupertinoSliverNavigationBar], which can
/// dynamically change size in response to scrolling.
final Widget? middle;
/// {@template flutter.cupertino.CupertinoNavigationBar.trailing}
/// Widget to place at the end of the navigation bar. Normally additional actions
/// taken on the page such as a search or edit function.
/// {@endtemplate}
final Widget? trailing;
/// {@template flutter.cupertino.CupertinoNavigationBar.backgroundColor}
/// The background color of the navigation bar. If it contains transparency, the
/// tab bar will automatically produce a blurring effect to the content
/// behind it. This behavior can be disabled by setting [enableBackgroundFilterBlur]
/// to false.
///
/// By default, the navigation bar's background is visible only when scrolled under.
/// This behavior can be controlled with [automaticBackgroundVisibility].
///
/// Defaults to [CupertinoTheme]'s `barBackgroundColor` if null.
/// {@endtemplate}
final Color? backgroundColor;
/// {@template flutter.cupertino.CupertinoNavigationBar.automaticBackgroundVisibility}
/// Whether the navigation bar appears transparent when no content is scrolled under.
///
/// If this is true, the navigation bar's background color will be transparent
/// until the content scrolls under it. If false, the navigation bar will always
/// use [backgroundColor] as its background color.
///
/// If the navigation bar is not a child of a [CupertinoPageScaffold], this has no effect.
///
/// This value defaults to true.
/// {@endtemplate}
final bool automaticBackgroundVisibility;
/// {@template flutter.cupertino.CupertinoNavigationBar.brightness}
/// The brightness of the specified [backgroundColor].
///
/// Setting this value changes the style of the system status bar. Typically
/// used to increase the contrast ratio of the system status bar over
/// [backgroundColor].
///
/// If set to null, the value of the property will be inferred from the relative
/// luminance of [backgroundColor].
/// {@endtemplate}
final Brightness? brightness;
/// {@template flutter.cupertino.CupertinoNavigationBar.padding}
/// Padding for the contents of the navigation bar.
///
/// If null, the navigation bar will adopt the following defaults:
///
/// * Vertically, contents will be sized to the same height as the navigation
/// bar itself minus the status bar.
/// * Horizontally, padding will be 16 pixels according to iOS specifications
/// unless the leading widget is an automatically inserted back button, in
/// which case the padding will be 0.
///
/// Vertical padding won't change the height of the nav bar.
/// {@endtemplate}
final EdgeInsetsDirectional? padding;
/// {@template flutter.cupertino.CupertinoNavigationBar.border}
/// The border of the navigation bar. By default renders a single pixel bottom border side.
///
/// If a border is null, the navigation bar will not display a border.
/// {@endtemplate}
final Border? border;
/// {@template flutter.cupertino.CupertinoNavigationBar.transitionBetweenRoutes}
/// Whether to transition between navigation bars.
///
/// When [transitionBetweenRoutes] is true, this navigation bar will transition
/// on top of the routes instead of inside it if the route being transitioned
/// to also has a [CupertinoNavigationBar] or a [CupertinoSliverNavigationBar]
/// with [transitionBetweenRoutes] set to true.
///
/// This transition will also occur on edge back swipe gestures like on iOS
/// but only if the previous page below has `maintainState` set to true on the
/// [PageRoute].
///
/// When set to true, only one navigation bar can be present per route unless
/// [heroTag] is also set.
///
/// This value defaults to true.
/// {@endtemplate}
final bool transitionBetweenRoutes;
/// {@template flutter.cupertino.CupertinoNavigationBar.enableBackgroundFilterBlur}
/// Whether to have a blur effect when a non-opaque background color is used.
///
/// When [enableBackgroundFilterBlur] is set to false, the blur effect will be
/// disabled. The behaviour of [enableBackgroundFilterBlur] will only be respected when
/// [automaticBackgroundVisibility] is false or until content scrolls under the navbar.
///
/// This value defaults to true.
/// {@endtemplate}
final bool enableBackgroundFilterBlur;
/// {@template flutter.cupertino.CupertinoNavigationBar.heroTag}
/// Tag for the navigation bar's Hero widget if [transitionBetweenRoutes] is true.
///
/// Defaults to a common tag between all [CupertinoNavigationBar] and
/// [CupertinoSliverNavigationBar] instances of the same [Navigator]. With the
/// default tag, all navigation bars of the same navigator can transition
/// between each other as long as there's only one navigation bar per route.
///
/// This [heroTag] can be overridden to manually handle having multiple
/// navigation bars per route or to transition between multiple
/// [Navigator]s.
///
/// To disable Hero transitions for this navigation bar, set
/// [transitionBetweenRoutes] to false.
/// {@endtemplate}
final Object heroTag;
/// A widget to place at the bottom of the navigation bar.
///
/// Only widgets that implement [PreferredSizeWidget] can be used at the
/// bottom of a navigation bar.
///
/// {@tool dartpad}
/// This example shows a [CupertinoSearchTextField] at the bottom of a
/// [CupertinoNavigationBar].
///
/// ** See code in examples/api/lib/cupertino/nav_bar/cupertino_navigation_bar.1.dart **
/// {@end-tool}
///
/// See also:
///
/// * [PreferredSize], which can be used to give an arbitrary widget a preferred size.
final PreferredSizeWidget? bottom;
/// True if the navigation bar's background color has no transparency.
@override
bool shouldFullyObstruct(BuildContext context) {
final Color backgroundColor =
CupertinoDynamicColor.maybeResolve(this.backgroundColor, context) ??
CupertinoTheme.of(context).barBackgroundColor;
return backgroundColor.alpha == 0xFF;
}
@override
Size get preferredSize {
final double bottomHeight = bottom?.preferredSize.height ?? 0.0;
final double effectiveLargeHeight = largeTitle != null
? _kNavBarLargeTitleHeightExtension
: 0.0;
return Size.fromHeight(_kNavBarPersistentHeight + bottomHeight + effectiveLargeHeight);
}
@override
State<CupertinoNavigationBar> createState() => _CupertinoNavigationBarState();
}
// A state class exists for the nav bar so that the keys of its sub-components
// don't change when rebuilding the nav bar, causing the sub-components to
// lose their own states.
class _CupertinoNavigationBarState extends State<CupertinoNavigationBar> {
late _NavigationBarStaticComponentsKeys keys;
ScrollNotificationObserverState? _scrollNotificationObserver;
double _scrollAnimationValue = 0.0;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_scrollNotificationObserver?.removeListener(_handleScrollNotification);
_scrollNotificationObserver = ScrollNotificationObserver.maybeOf(context);
_scrollNotificationObserver?.addListener(_handleScrollNotification);
}
@override
void dispose() {
if (_scrollNotificationObserver != null) {
_scrollNotificationObserver!.removeListener(_handleScrollNotification);
_scrollNotificationObserver = null;
}
super.dispose();
}
@override
void initState() {
super.initState();
keys = _NavigationBarStaticComponentsKeys();
}
void _handleScrollNotification(ScrollNotification notification) {
if (notification is ScrollUpdateNotification && notification.depth == 0) {
final ScrollMetrics metrics = notification.metrics;
final double oldScrollAnimationValue = _scrollAnimationValue;
var scrollExtent = 0.0;
switch (metrics.axisDirection) {
case AxisDirection.up:
// Scroll view is reversed
scrollExtent = metrics.extentAfter;
case AxisDirection.down:
scrollExtent = metrics.extentBefore;
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 (scrollExtent >= 0 && scrollExtent < _kNavBarScrollUnderAnimationExtent) {
setState(() {
_scrollAnimationValue = clampDouble(
scrollExtent / _kNavBarScrollUnderAnimationExtent,
0,
1,
);
});
} else if (scrollExtent > _kNavBarScrollUnderAnimationExtent &&
oldScrollAnimationValue != 1.0) {
setState(() {
_scrollAnimationValue = 1.0;
});
} else if (scrollExtent <= 0 && oldScrollAnimationValue != 0.0) {
setState(() {
_scrollAnimationValue = 0.0;
});
}
}
}
@override
Widget build(BuildContext context) {
// The static navigation bar does not expand or collapse (see CupertinoSliverNavigationBar),
// it will either display the collapsed nav bar with middle, or the expanded with largeTitle.
assert(widget.middle == null || widget.largeTitle == null);
final Color backgroundColor =
CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context) ??
CupertinoTheme.of(context).barBackgroundColor;
final Color? parentPageScaffoldBackgroundColor = CupertinoPageScaffoldBackgroundColor.maybeOf(
context,
);
final Border? initialBorder =
widget.automaticBackgroundVisibility && parentPageScaffoldBackgroundColor != null
? _kTransparentNavBarBorder
: widget.border;
final Border? effectiveBorder = widget.border == null
? null
: Border.lerp(initialBorder, widget.border, _scrollAnimationValue);
final Color effectiveBackgroundColor =
widget.automaticBackgroundVisibility && parentPageScaffoldBackgroundColor != null
? Color.lerp(parentPageScaffoldBackgroundColor, backgroundColor, _scrollAnimationValue) ??
backgroundColor
: backgroundColor;
final double bottomHeight = widget.bottom?.preferredSize.height ?? 0.0;
final double persistentHeight =
_kNavBarPersistentHeight + bottomHeight + MediaQuery.paddingOf(context).top;
final double largeHeight = persistentHeight + _kNavBarLargeTitleHeightExtension;
final components = _NavigationBarStaticComponents(
keys: keys,
route: ModalRoute.of(context),
userLeading: widget.leading,
automaticallyImplyLeading: widget.automaticallyImplyLeading,
automaticallyImplyTitle: widget.automaticallyImplyMiddle,
previousPageTitle: widget.previousPageTitle,
userMiddle: widget.middle,
userTrailing: widget.trailing,
padding: widget.padding,
userLargeTitle: widget.largeTitle,
userBottom: widget.bottom,
large: widget.largeTitle != null,
staticBar: true, // This one does not scroll
context: context,
);
// Standard persistent components
Widget navBar = _PersistentNavigationBar(
components: components,
padding: widget.padding,
middleVisible: widget.largeTitle == null,
);
if (widget.largeTitle != null) {
// Large nav bar
navBar = ConstrainedBox(
constraints: BoxConstraints(maxHeight: largeHeight),
child: Column(
children: <Widget>[
navBar,
Expanded(
child: Padding(
padding: const EdgeInsetsDirectional.only(
start: _kNavBarEdgePadding,
bottom: _kNavBarBottomPadding,
),
child: Semantics(
header: true,
child: DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
child: _LargeTitle(
height: _kNavBarLargeTitleHeightExtension,
child: components.largeTitle,
),
),
),
),
),
if (widget.bottom != null)
SizedBox(height: bottomHeight, child: components.navBarBottom),
],
),
);
} else {
// Small nav bar
navBar = ConstrainedBox(
constraints: BoxConstraints(maxHeight: persistentHeight),
child: Column(
children: <Widget>[
navBar,
if (widget.bottom != null)
SizedBox(height: bottomHeight, child: components.navBarBottom),
],
),
);
}
navBar = _wrapWithBackground(
border: effectiveBorder,
backgroundColor: effectiveBackgroundColor,
brightness: widget.brightness,
enableBackgroundFilterBlur: widget.enableBackgroundFilterBlur,
child: DefaultTextStyle(style: CupertinoTheme.of(context).textTheme.textStyle, child: navBar),
);
if (!widget.transitionBetweenRoutes || !_isTransitionable(context)) {
// Lint ignore to maintain backward compatibility.
return navBar;
}
return Builder(
// Get the context that might have a possibly changed CupertinoTheme.
builder: (BuildContext context) {
return Hero(
tag: widget.heroTag == _defaultHeroTag ? _HeroTag(Navigator.of(context)) : widget.heroTag,
createRectTween: _linearTranslateWithLargestRectSizeTween,
placeholderBuilder: _navBarHeroLaunchPadBuilder,
flightShuttleBuilder: _navBarHeroFlightShuttleBuilder,
transitionOnUserGestures: true,
child: _TransitionableNavigationBar(
componentsKeys: keys,
backgroundColor: effectiveBackgroundColor,
backButtonTextStyle: CupertinoTheme.of(context).textTheme.navActionTextStyle,
titleTextStyle: CupertinoTheme.of(context).textTheme.navTitleTextStyle,
largeTitleTextStyle: CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle,
border: effectiveBorder,
hasUserMiddle: widget.middle != null,
largeExpanded: widget.largeTitle != null,
searchable: false,
automaticBackgroundVisibility: widget.automaticBackgroundVisibility,
child: navBar,
),
);
},
);
}
}
/// An iOS-styled navigation bar with iOS-11-style large titles using slivers.
///
/// The [CupertinoSliverNavigationBar] must be placed in a sliver group such
/// as the [CustomScrollView].
///
/// This navigation bar consists of two sections, a pinned static section on top
/// and a sliding section containing iOS-11-style large title below it.
///
/// It should be placed at top of the screen and automatically accounts for
/// the iOS status bar.
///
/// This navigation bar is expanded only in portrait orientation. In landscape
/// mode, the navigation bar remains permanently collapsed. The navigation bar
/// also collapses when scrolling in portrait mode.
///
/// Minimally, a [largeTitle] widget will appear in the middle of the app bar
/// when the sliver is collapsed and transfer to the area below in larger font
/// when the sliver is expanded. This expanded view will only trigger in
/// portrait orientation, while in landscape mode the bar will stay in its
/// collapsed view.
///
/// For advanced uses, an optional [middle] widget
/// can be supplied to show a different widget in the middle of the navigation
/// bar when the sliver is collapsed.
///
/// Like [CupertinoNavigationBar], it also supports a [leading] and [trailing]
/// widget on the static section on top that remains while scrolling.
///
/// The [leading] widget will automatically be a back chevron icon button (or a
/// cancel button in case of a fullscreen dialog) to pop the current route if none
/// is provided and [automaticallyImplyLeading] is true (true by default).
///
/// The [largeTitle] widget will automatically be a title text from the current
/// [CupertinoPageRoute] if none is provided and [automaticallyImplyTitle] is
/// true (true by default).
///
/// When [transitionBetweenRoutes] is true, this navigation bar will transition
/// on top of the routes instead of inside them if the route being transitioned
/// to also has a [CupertinoNavigationBar] or a [CupertinoSliverNavigationBar]
/// with [transitionBetweenRoutes] set to true. If [transitionBetweenRoutes] is
/// true, none of the [Widget] parameters can contain any [GlobalKey]s in their
/// subtrees since those widgets will exist in multiple places in the tree
/// simultaneously.
///
/// By default, only one [CupertinoNavigationBar] or [CupertinoSliverNavigationBar]
/// should be present in each [PageRoute] to support the default transitions.
/// Use [transitionBetweenRoutes] or [heroTag] to customize the transition
/// behavior for multiple navigation bars per route.
///
/// The [stretch] parameter determines whether the nav bar should stretch to
/// fill the over-scroll area. The nav bar can still expand and contract as the
/// user scrolls, but it will also stretch when the user over-scrolls if the
/// [stretch] value is `true`. Defaults to `false`.
///
/// {@tool dartpad}
/// This example shows [CupertinoSliverNavigationBar] in action inside a [CustomScrollView].
///
/// ** See code in examples/api/lib/cupertino/nav_bar/cupertino_sliver_nav_bar.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// To add a widget to the bottom of the nav bar, wrap it with [PreferredSize] and provide its fully extended size.
///
/// ** See code in examples/api/lib/cupertino/nav_bar/cupertino_sliver_nav_bar.2.dart **
/// {@end-tool}
///
/// See also:
///
/// * [CupertinoNavigationBar], an iOS navigation bar for use on non-scrolling
/// pages.
/// * [CustomScrollView], a ScrollView that creates custom scroll effects using slivers.
/// * <https://developer.apple.com/design/human-interface-guidelines/ios/bars/navigation-bars/>
class CupertinoSliverNavigationBar extends StatefulWidget {
/// Creates a navigation bar for scrolling lists.
///
/// If [automaticallyImplyTitle] is false, then the [largeTitle] argument is
/// required.
const CupertinoSliverNavigationBar({
super.key,
this.largeTitle,
this.leading,
this.automaticallyImplyLeading = true,
this.automaticallyImplyTitle = true,
this.alwaysShowMiddle = true,
this.previousPageTitle,
this.middle,
this.trailing,
this.border = _kDefaultNavBarBorder,
this.backgroundColor,
this.automaticBackgroundVisibility = true,
this.enableBackgroundFilterBlur = true,
this.brightness,
this.padding,
this.transitionBetweenRoutes = true,
this.heroTag = _defaultHeroTag,
this.stretch = false,
this.bottom,
this.bottomMode,
}) : assert(
automaticallyImplyTitle || largeTitle != null,
'No largeTitle has been provided but automaticallyImplyTitle is also '
'false. Either provide a largeTitle or set automaticallyImplyTitle to '
'true.',
),
assert(
bottomMode == null || bottom != null,
'A bottomMode was provided without a corresponding bottom.',
),
onSearchableBottomTap = null,
searchField = null,
_searchable = false;
/// A navigation bar for scrolling lists that integrates a provided search
/// field directly into the navigation bar.
///
/// This search-enabled navigation bar is functionally equivalent to
/// the standard [CupertinoSliverNavigationBar] constructor, but with the
/// addition of [searchField], which sits at the bottom of the navigation bar.
///
/// When the search field is tapped, [leading], [trailing], [middle], and
/// [largeTitle] all collapse, causing the search field to animate to the
/// 'top' of the navigation bar. A 'Cancel' button is presented next to the
/// active [searchField], which when tapped, closes the search view, bringing
/// the navigation bar back to its initial state.
///
/// If [automaticallyImplyTitle] is false, then the [largeTitle] argument is