-
Notifications
You must be signed in to change notification settings - Fork 26.7k
/
nav_bar.dart
2493 lines (2227 loc) · 86.6 KB
/
nav_bar.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
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 'page_scaffold.dart';
import 'route.dart';
import 'theme.dart';
/// 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
/// form 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;
const double _kNavBarEdgePadding = 16.0;
const double _kNavBarBottomPadding = 8.0;
const double _kNavBarBackButtonTapWidth = 50.0;
/// 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
),
);
// 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.size,
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 size to impose on `child`.
final Size size;
// 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: size.width,
height: size.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,
}) {
Widget 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) {
case Brightness.dark:
overlayStyle = SystemUiOverlayStyle.light;
break;
case Brightness.light:
overlayStyle = SystemUiOverlayStyle.dark;
break;
}
result = AnnotatedRegion<SystemUiOverlayStyle>(
value: overlayStyle,
child: result,
);
}
final DecoratedBox childWithBackground = DecoratedBox(
decoration: BoxDecoration(
border: border,
color: backgroundColor,
),
child: result,
);
if (backgroundColor.alpha == 0xFF) {
return childWithBackground;
}
return ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
child: childWithBackground,
),
);
}
// 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;
}
/// An iOS-styled navigation bar.
///
/// The navigation bar is a toolbar that minimally consists of a widget, normally
/// a page title, in the [middle] of the toolbar.
///
/// It also supports a [leading] and [trailing] widget before and after the
/// [middle] widget while keeping the [middle] widget centered.
///
/// The [leading] widget will automatically be a back chevron icon button (or a
/// close button in case of a fullscreen dialog) to pop the current route if none
/// is provided and [automaticallyImplyLeading] is true (true by default).
///
/// The [middle] widget will automatically be a title text from the current
/// [CupertinoPageRoute] if none is provided and [automaticallyImplyMiddle] is
/// true (true by default).
///
/// It should be placed at top of the screen and automatically accounts 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.
///
/// 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]
/// has its text scale factor set to 1.0 and does not respond to text scale factor
/// changes from the operating system, to match the native iOS behavior. To override
/// this behavior, wrap each of the `navigationBar`'s components inside a [MediaQuery]
/// with the desired [MediaQueryData.textScaleFactor] value. The text scale factor
/// value from the operating system can be retrieved in many ways, such as querying
/// [MediaQuery.textScaleFactorOf] against [CupertinoApp]'s [BuildContext].
///
/// {@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}
///
/// 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 navigation bar in the iOS style.
const CupertinoNavigationBar({
super.key,
this.leading,
this.automaticallyImplyLeading = true,
this.automaticallyImplyMiddle = true,
this.previousPageTitle,
this.middle,
this.trailing,
this.border = _kDefaultNavBarBorder,
this.backgroundColor,
this.brightness,
this.padding,
this.transitionBetweenRoutes = true,
this.heroTag = _defaultHeroTag,
}) : assert(automaticallyImplyLeading != null),
assert(automaticallyImplyMiddle != null),
assert(transitionBetweenRoutes != null),
assert(
heroTag != null,
'heroTag cannot be null. Use transitionBetweenRoutes = false to '
'disable Hero transition on this navigation bar.',
),
assert(
!transitionBetweenRoutes || identical(heroTag, _defaultHeroTag),
'Cannot specify a heroTag override if this navigation bar does not '
'transition due to transitionBetweenRoutes = false.',
);
/// {@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 'Close' 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].
///
/// This value cannot be null.
/// {@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.
///
/// This value cannot be null.
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;
/// Widget to place in the middle of the navigation bar. Normally a title or
/// a segmented control.
///
/// If null and [automaticallyImplyMiddle] is true, an appropriate [Text]
/// title will be created if the current route is a [CupertinoPageRoute] and
/// has a `title`.
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;
// TODO(xster): https://github.com/flutter/flutter/issues/10469 implement
// support for double row navigation bars.
/// {@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.
///
/// Defaults to [CupertinoTheme]'s `barBackgroundColor` if null.
/// {@endtemplate}
final Color? backgroundColor;
/// {@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 and cannot be null.
/// {@endtemplate}
final bool transitionBetweenRoutes;
/// {@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.
///
/// Cannot be null. To disable Hero transitions for this navigation bar,
/// set [transitionBetweenRoutes] to false.
/// {@endtemplate}
final Object heroTag;
/// 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 {
return const Size.fromHeight(_kNavBarPersistentHeight);
}
@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;
@override
void initState() {
super.initState();
keys = _NavigationBarStaticComponentsKeys();
}
@override
Widget build(BuildContext context) {
final Color backgroundColor =
CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context) ?? CupertinoTheme.of(context).barBackgroundColor;
final _NavigationBarStaticComponents 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: null,
large: false,
);
final Widget navBar = _wrapWithBackground(
border: widget.border,
backgroundColor: backgroundColor,
brightness: widget.brightness,
child: DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: _PersistentNavigationBar(
components: components,
padding: widget.padding,
),
),
);
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: backgroundColor,
backButtonTextStyle: CupertinoTheme.of(context).textTheme.navActionTextStyle,
titleTextStyle: CupertinoTheme.of(context).textTheme.navTitleTextStyle,
largeTitleTextStyle: null,
border: widget.border,
hasUserMiddle: widget.middle != null,
largeExpanded: false,
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.
///
/// 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.
///
/// 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
/// close 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.
///
/// [CupertinoSliverNavigationBar] has its text scale factor set to 1.0 by default
/// and does not respond to text scale factor changes from the operating system,
/// to match the native iOS behavior. To override this behavior, wrap each of the
/// [CupertinoSliverNavigationBar]'s components inside a [MediaQuery] with the
/// desired [MediaQueryData.textScaleFactor] value. The text scale factor value
/// from the operating system can be retrieved in many ways, such as querying
/// [MediaQuery.textScaleFactorOf] against [CupertinoApp]'s [BuildContext].
///
/// 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}
///
/// 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.
///
/// The [largeTitle] argument is required and must not be null.
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.brightness,
this.padding,
this.transitionBetweenRoutes = true,
this.heroTag = _defaultHeroTag,
this.stretch = false,
}) : assert(automaticallyImplyLeading != null),
assert(automaticallyImplyTitle != null),
assert(
automaticallyImplyTitle == true || largeTitle != null,
'No largeTitle has been provided but automaticallyImplyTitle is also '
'false. Either provide a largeTitle or set automaticallyImplyTitle to '
'true.',
);
/// The navigation bar's title.
///
/// This text will appear in the top static navigation bar when collapsed and
/// below the navigation bar, in a larger font, when expanded.
///
/// A suitable [DefaultTextStyle] is provided around this widget as it is
/// moved around, to change its font size.
///
/// If [middle] is null, then the [largeTitle] widget will be inserted into
/// the tree in two places when transitioning from the collapsed state to the
/// expanded state. It is therefore imperative that this subtree not contain
/// any [GlobalKey]s, and that it not rely on maintaining state (for example,
/// animations will not survive the transition from one location to the other,
/// and may in fact be visible in two places at once during the transition).
///
/// 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 parameter must either be non-null or the route must have a title
/// ([CupertinoPageRoute.title]) and [automaticallyImplyTitle] must be true.
final Widget? largeTitle;
/// {@macro flutter.cupertino.CupertinoNavigationBar.leading}
///
/// This widget is visible in both collapsed and expanded states.
final Widget? leading;
/// {@macro flutter.cupertino.CupertinoNavigationBar.automaticallyImplyLeading}
final bool automaticallyImplyLeading;
/// Controls whether we should try to imply the [largeTitle] widget if null.
///
/// If true and [largeTitle] is null, automatically fill in a [Text] widget
/// with the current route's `title` if the route is a [CupertinoPageRoute].
/// If [largeTitle] widget is not null, this parameter has no effect.
///
/// This value cannot be null.
final bool automaticallyImplyTitle;
/// Controls whether [middle] widget should always be visible (even in
/// expanded state).
///
/// If true (default) and [middle] is not null, [middle] widget is always
/// visible. If false, [middle] widget is visible only in collapsed state if
/// it is provided.
///
/// This should be set to false if you only want to show [largeTitle] in
/// expanded state and [middle] in collapsed state.
final bool alwaysShowMiddle;
/// {@macro flutter.cupertino.CupertinoNavigationBar.previousPageTitle}
final String? previousPageTitle;
/// A widget to place in the middle of the static navigation bar instead of
/// the [largeTitle].
///
/// This widget is visible in both collapsed and expanded states if
/// [alwaysShowMiddle] is true, otherwise just in collapsed state. The text
/// supplied in [largeTitle] will no longer appear in collapsed state if a
/// [middle] widget is provided.
final Widget? middle;
/// {@macro flutter.cupertino.CupertinoNavigationBar.trailing}
///
/// This widget is visible in both collapsed and expanded states.
final Widget? trailing;
/// {@macro flutter.cupertino.CupertinoNavigationBar.backgroundColor}
final Color? backgroundColor;
/// {@macro flutter.cupertino.CupertinoNavigationBar.brightness}
final Brightness? brightness;
/// {@macro flutter.cupertino.CupertinoNavigationBar.padding}
final EdgeInsetsDirectional? padding;
/// {@macro flutter.cupertino.CupertinoNavigationBar.border}
final Border? border;
/// {@macro flutter.cupertino.CupertinoNavigationBar.transitionBetweenRoutes}
final bool transitionBetweenRoutes;
/// {@macro flutter.cupertino.CupertinoNavigationBar.heroTag}
final Object heroTag;
/// True if the navigation bar's background color has no transparency.
bool get opaque => backgroundColor?.alpha == 0xFF;
/// 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`.
///
/// When set to `true`, the nav bar will prevent subsequent slivers from
/// accessing overscrolls. This may be undesirable for using overscroll-based
/// widgets like the [CupertinoSliverRefreshControl].
///
/// Defaults to `false`.
final bool stretch;
@override
State<CupertinoSliverNavigationBar> createState() => _CupertinoSliverNavigationBarState();
}
// 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 _CupertinoSliverNavigationBarState extends State<CupertinoSliverNavigationBar> {
late _NavigationBarStaticComponentsKeys keys;
@override
void initState() {
super.initState();
keys = _NavigationBarStaticComponentsKeys();
}
@override
Widget build(BuildContext context) {
final _NavigationBarStaticComponents components = _NavigationBarStaticComponents(
keys: keys,
route: ModalRoute.of(context),
userLeading: widget.leading,
automaticallyImplyLeading: widget.automaticallyImplyLeading,
automaticallyImplyTitle: widget.automaticallyImplyTitle,
previousPageTitle: widget.previousPageTitle,
userMiddle: widget.middle,
userTrailing: widget.trailing,
userLargeTitle: widget.largeTitle,
padding: widget.padding,
large: true,
);
return MediaQuery(
data: MediaQuery.of(context).copyWith(textScaleFactor: 1),
child: SliverPersistentHeader(
pinned: true, // iOS navigation bars are always pinned.
delegate: _LargeTitleNavigationBarSliverDelegate(
keys: keys,
components: components,
userMiddle: widget.middle,
backgroundColor: CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context) ?? CupertinoTheme.of(context).barBackgroundColor,
brightness: widget.brightness,
border: widget.border,
padding: widget.padding,
actionsForegroundColor: CupertinoTheme.of(context).primaryColor,
transitionBetweenRoutes: widget.transitionBetweenRoutes,
heroTag: widget.heroTag,
persistentHeight: _kNavBarPersistentHeight + MediaQuery.paddingOf(context).top,
alwaysShowMiddle: widget.alwaysShowMiddle && widget.middle != null,
stretchConfiguration: widget.stretch ? OverScrollHeaderStretchConfiguration() : null,
),
),
);
}
}
class _LargeTitleNavigationBarSliverDelegate
extends SliverPersistentHeaderDelegate with DiagnosticableTreeMixin {
_LargeTitleNavigationBarSliverDelegate({
required this.keys,
required this.components,
required this.userMiddle,
required this.backgroundColor,
required this.brightness,
required this.border,
required this.padding,
required this.actionsForegroundColor,
required this.transitionBetweenRoutes,
required this.heroTag,
required this.persistentHeight,
required this.alwaysShowMiddle,
required this.stretchConfiguration,
}) : assert(persistentHeight != null),
assert(alwaysShowMiddle != null),
assert(transitionBetweenRoutes != null);
final _NavigationBarStaticComponentsKeys keys;
final _NavigationBarStaticComponents components;
final Widget? userMiddle;
final Color backgroundColor;
final Brightness? brightness;
final Border? border;
final EdgeInsetsDirectional? padding;
final Color actionsForegroundColor;
final bool transitionBetweenRoutes;
final Object heroTag;
final double persistentHeight;
final bool alwaysShowMiddle;
@override
double get minExtent => persistentHeight;
@override
double get maxExtent => persistentHeight + _kNavBarLargeTitleHeightExtension;
@override
OverScrollHeaderStretchConfiguration? stretchConfiguration;
@override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
final bool showLargeTitle = shrinkOffset < maxExtent - minExtent - _kNavBarShowLargeTitleThreshold;
final _PersistentNavigationBar persistentNavigationBar =
_PersistentNavigationBar(
components: components,
padding: padding,
// If a user specified middle exists, always show it. Otherwise, show
// title when sliver is collapsed.
middleVisible: alwaysShowMiddle ? null : !showLargeTitle,
);
final Widget navBar = _wrapWithBackground(
border: border,
backgroundColor: CupertinoDynamicColor.resolve(backgroundColor, context),
brightness: brightness,
child: DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Positioned(
top: persistentHeight,
left: 0.0,
right: 0.0,
bottom: 0.0,
child: ClipRect(
child: Padding(
padding: const EdgeInsetsDirectional.only(
start: _kNavBarEdgePadding,
bottom: _kNavBarBottomPadding
),
child: SafeArea(
top: false,
bottom: false,
child: AnimatedOpacity(
opacity: showLargeTitle ? 1.0 : 0.0,
duration: _kNavBarTitleFadeDuration,
child: Semantics(
header: true,
child: DefaultTextStyle(
style: CupertinoTheme.of(context)
.textTheme
.navLargeTitleTextStyle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
child: _LargeTitle(
child: components.largeTitle,
),
),
),
),
),
),
),
),
Positioned(
left: 0.0,
right: 0.0,
top: 0.0,
child: persistentNavigationBar,
),
],
),
),
);
if (!transitionBetweenRoutes || !_isTransitionable(context)) {
return navBar;
}
return Hero(
tag: heroTag == _defaultHeroTag
? _HeroTag(Navigator.of(context))
: heroTag,
createRectTween: _linearTranslateWithLargestRectSizeTween,
flightShuttleBuilder: _navBarHeroFlightShuttleBuilder,
placeholderBuilder: _navBarHeroLaunchPadBuilder,
transitionOnUserGestures: true,
// This is all the way down here instead of being at the top level of
// CupertinoSliverNavigationBar like CupertinoNavigationBar because it
// needs to wrap the top level RenderBox rather than a RenderSliver.
child: _TransitionableNavigationBar(
componentsKeys: keys,
backgroundColor: CupertinoDynamicColor.resolve(backgroundColor, context),
backButtonTextStyle: CupertinoTheme.of(context).textTheme.navActionTextStyle,
titleTextStyle: CupertinoTheme.of(context).textTheme.navTitleTextStyle,
largeTitleTextStyle: CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle,
border: border,
hasUserMiddle: userMiddle != null,
largeExpanded: showLargeTitle,
child: navBar,
),
);
}
@override
bool shouldRebuild(_LargeTitleNavigationBarSliverDelegate oldDelegate) {
return components != oldDelegate.components
|| userMiddle != oldDelegate.userMiddle
|| backgroundColor != oldDelegate.backgroundColor
|| border != oldDelegate.border
|| padding != oldDelegate.padding
|| actionsForegroundColor != oldDelegate.actionsForegroundColor
|| transitionBetweenRoutes != oldDelegate.transitionBetweenRoutes
|| persistentHeight != oldDelegate.persistentHeight
|| alwaysShowMiddle != oldDelegate.alwaysShowMiddle
|| heroTag != oldDelegate.heroTag;
}
}
/// The large title of the navigation bar.
///
/// Magnifies on over-scroll when [CupertinoSliverNavigationBar.stretch]
/// parameter is true.
class _LargeTitle extends SingleChildRenderObjectWidget {
const _LargeTitle({ super.child });
@override
_RenderLargeTitle createRenderObject(BuildContext context) {
return _RenderLargeTitle(alignment: AlignmentDirectional.bottomStart.resolve(Directionality.of(context)));
}
@override
void updateRenderObject(BuildContext context, _RenderLargeTitle renderObject) {
renderObject.alignment = AlignmentDirectional.bottomStart.resolve(Directionality.of(context));
}
}
class _RenderLargeTitle extends RenderShiftedBox {
_RenderLargeTitle({
required Alignment alignment,
}) : _alignment = alignment,
super(null);
Alignment get alignment => _alignment;
Alignment _alignment;
set alignment(Alignment value) {
if (_alignment == value) {
return;
}
_alignment = value;
markNeedsLayout();
}
double _scale = 1.0;
@override
void performLayout() {
final RenderBox? child = this.child;
Size childSize = Size.zero;
size = constraints.biggest;
if (child == null) {
return;
}
final BoxConstraints childConstriants = constraints.widthConstraints().loosen();
child.layout(childConstriants, parentUsesSize: true);
final double maxScale = child.size.width != 0.0
? clampDouble(constraints.maxWidth / child.size.width, 1.0, 1.1)
: 1.1;
_scale = clampDouble(
1.0 + (constraints.maxHeight - (_kNavBarLargeTitleHeightExtension - _kNavBarBottomPadding)) / (_kNavBarLargeTitleHeightExtension - _kNavBarBottomPadding) * 0.03,
1.0,
maxScale,
);
childSize = child.size * _scale;
final BoxParentData childParentData = child.parentData! as BoxParentData;
childParentData.offset = alignment.alongOffset(size - childSize as Offset);
}
@override
void applyPaintTransform(RenderBox child, Matrix4 transform) {
assert(child == this.child);
super.applyPaintTransform(child, transform);
transform.scale(_scale, _scale);
}
@override
void paint(PaintingContext context, Offset offset) {
final RenderBox? child = this.child;
if (child == null) {