-
Notifications
You must be signed in to change notification settings - Fork 26.8k
/
scaffold.dart
3340 lines (3057 loc) · 128 KB
/
scaffold.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:async';
import 'dart:collection';
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart' show DragStartBehavior;
import 'package:flutter/widgets.dart';
import 'app_bar.dart';
import 'banner.dart';
import 'banner_theme.dart';
import 'bottom_sheet.dart';
import 'colors.dart';
import 'curves.dart';
import 'debug.dart';
import 'divider.dart';
import 'drawer.dart';
import 'flexible_space_bar.dart';
import 'floating_action_button.dart';
import 'floating_action_button_location.dart';
import 'material.dart';
import 'snack_bar.dart';
import 'snack_bar_theme.dart';
import 'theme.dart';
// Examples can assume:
// late TabController tabController;
// void setState(VoidCallback fn) { }
// late String appBarTitle;
// late int tabCount;
// late TickerProvider tickerProvider;
const FloatingActionButtonLocation _kDefaultFloatingActionButtonLocation = FloatingActionButtonLocation.endFloat;
const FloatingActionButtonAnimator _kDefaultFloatingActionButtonAnimator = FloatingActionButtonAnimator.scaling;
const Curve _standardBottomSheetCurve = standardEasing;
// When the top of the BottomSheet crosses this threshold, it will start to
// shrink the FAB and show a scrim.
const double _kBottomSheetDominatesPercentage = 0.3;
const double _kMinBottomSheetScrimOpacity = 0.1;
const double _kMaxBottomSheetScrimOpacity = 0.6;
enum _ScaffoldSlot {
body,
appBar,
bodyScrim,
bottomSheet,
snackBar,
materialBanner,
persistentFooter,
bottomNavigationBar,
floatingActionButton,
drawer,
endDrawer,
statusBar,
}
/// Manages [SnackBar]s and [MaterialBanner]s for descendant [Scaffold]s.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=lytQi-slT5Y}
///
/// This class provides APIs for showing snack bars and material banners at the
/// bottom and top of the screen, respectively.
///
/// To display one of these notifications, obtain the [ScaffoldMessengerState]
/// for the current [BuildContext] via [ScaffoldMessenger.of] and use the
/// [ScaffoldMessengerState.showSnackBar] or the
/// [ScaffoldMessengerState.showMaterialBanner] functions.
///
/// When the [ScaffoldMessenger] has nested [Scaffold] descendants, the
/// ScaffoldMessenger will only present the notification to the root Scaffold of
/// the subtree of Scaffolds. In order to show notifications for the inner, nested
/// Scaffolds, set a new scope by instantiating a new ScaffoldMessenger in
/// between the levels of nesting.
///
/// {@tool dartpad}
/// Here is an example of showing a [SnackBar] when the user presses a button.
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_messenger.0.dart **
/// {@end-tool}
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=lytQi-slT5Y}
///
/// See also:
///
/// * [SnackBar], which is a temporary notification typically shown near the
/// bottom of the app using the [ScaffoldMessengerState.showSnackBar] method.
/// * [MaterialBanner], which is a temporary notification typically shown at the
/// top of the app using the [ScaffoldMessengerState.showMaterialBanner] method.
/// * [debugCheckHasScaffoldMessenger], which asserts that the given context
/// has a [ScaffoldMessenger] ancestor.
/// * Cookbook: [Display a SnackBar](https://flutter.dev/docs/cookbook/design/snackbars)
class ScaffoldMessenger extends StatefulWidget {
/// Creates a widget that manages [SnackBar]s for [Scaffold] descendants.
const ScaffoldMessenger({
super.key,
required this.child,
});
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
/// The state from the closest instance of this class that encloses the given
/// context.
///
/// {@tool dartpad}
/// Typical usage of the [ScaffoldMessenger.of] function is to call it in
/// response to a user gesture or an application state change.
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_messenger.of.0.dart **
/// {@end-tool}
///
/// A less elegant but more expedient solution is to assign a [GlobalKey] to the
/// [ScaffoldMessenger], then use the `key.currentState` property to obtain the
/// [ScaffoldMessengerState] rather than using the [ScaffoldMessenger.of]
/// function. The [MaterialApp.scaffoldMessengerKey] refers to the root
/// ScaffoldMessenger that is provided by default.
///
/// {@tool dartpad}
/// Sometimes [SnackBar]s are produced by code that doesn't have ready access
/// to a valid [BuildContext]. One such example of this is when you show a
/// SnackBar from a method outside of the `build` function. In these
/// cases, you can assign a [GlobalKey] to the [ScaffoldMessenger]. This
/// example shows a key being used to obtain the [ScaffoldMessengerState]
/// provided by the [MaterialApp].
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_messenger.of.1.dart **
/// {@end-tool}
///
/// If there is no [ScaffoldMessenger] in scope, then this will assert in
/// debug mode, and throw an exception in release mode.
///
/// See also:
///
/// * [maybeOf], which is a similar function but will return null instead of
/// throwing if there is no [ScaffoldMessenger] ancestor.
/// * [debugCheckHasScaffoldMessenger], which asserts that the given context
/// has a [ScaffoldMessenger] ancestor.
static ScaffoldMessengerState of(BuildContext context) {
assert(debugCheckHasScaffoldMessenger(context));
final _ScaffoldMessengerScope scope = context.dependOnInheritedWidgetOfExactType<_ScaffoldMessengerScope>()!;
return scope._scaffoldMessengerState;
}
/// The state from the closest instance of this class that encloses the given
/// context, if any.
///
/// Will return null if a [ScaffoldMessenger] is not found in the given context.
///
/// See also:
///
/// * [of], which is a similar function, except that it will throw an
/// exception if a [ScaffoldMessenger] is not found in the given context.
static ScaffoldMessengerState? maybeOf(BuildContext context) {
final _ScaffoldMessengerScope? scope = context.dependOnInheritedWidgetOfExactType<_ScaffoldMessengerScope>();
return scope?._scaffoldMessengerState;
}
@override
ScaffoldMessengerState createState() => ScaffoldMessengerState();
}
/// State for a [ScaffoldMessenger].
///
/// A [ScaffoldMessengerState] object can be used to [showSnackBar] or
/// [showMaterialBanner] for every registered [Scaffold] that is a descendant of
/// the associated [ScaffoldMessenger]. Scaffolds will register to receive
/// [SnackBar]s and [MaterialBanner]s from their closest ScaffoldMessenger
/// ancestor.
///
/// Typically obtained via [ScaffoldMessenger.of].
class ScaffoldMessengerState extends State<ScaffoldMessenger> with TickerProviderStateMixin {
final LinkedHashSet<ScaffoldState> _scaffolds = LinkedHashSet<ScaffoldState>();
final Queue<ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>> _materialBanners = Queue<ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>>();
AnimationController? _materialBannerController;
final Queue<ScaffoldFeatureController<SnackBar, SnackBarClosedReason>> _snackBars = Queue<ScaffoldFeatureController<SnackBar, SnackBarClosedReason>>();
AnimationController? _snackBarController;
Timer? _snackBarTimer;
bool? _accessibleNavigation;
@override
void didChangeDependencies() {
final bool accessibleNavigation = MediaQuery.accessibleNavigationOf(context);
// If we transition from accessible navigation to non-accessible navigation
// and there is a SnackBar that would have timed out that has already
// completed its timer, dismiss that SnackBar. If the timer hasn't finished
// yet, let it timeout as normal.
if ((_accessibleNavigation ?? false)
&& !accessibleNavigation
&& _snackBarTimer != null
&& !_snackBarTimer!.isActive) {
hideCurrentSnackBar(reason: SnackBarClosedReason.timeout);
}
_accessibleNavigation = accessibleNavigation;
super.didChangeDependencies();
}
void _register(ScaffoldState scaffold) {
_scaffolds.add(scaffold);
if (_isRoot(scaffold)) {
if (_snackBars.isNotEmpty) {
scaffold._updateSnackBar();
}
if (_materialBanners.isNotEmpty) {
scaffold._updateMaterialBanner();
}
}
}
void _unregister(ScaffoldState scaffold) {
final bool removed = _scaffolds.remove(scaffold);
// ScaffoldStates should only be removed once.
assert(removed);
}
void _updateScaffolds() {
for (final ScaffoldState scaffold in _scaffolds) {
if (_isRoot(scaffold)) {
scaffold._updateSnackBar();
scaffold._updateMaterialBanner();
}
}
}
// Nested Scaffolds are handled by the ScaffoldMessenger by only presenting a
// MaterialBanner or SnackBar in the root Scaffold of the nested set.
bool _isRoot(ScaffoldState scaffold) {
final ScaffoldState? parent = scaffold.context.findAncestorStateOfType<ScaffoldState>();
return parent == null || !_scaffolds.contains(parent);
}
// SNACKBAR API
/// Shows a [SnackBar] across all registered [Scaffold]s. Scaffolds register
/// to receive snack bars from their closest [ScaffoldMessenger] ancestor.
/// If there are several registered scaffolds the snack bar is shown
/// simultaneously on all of them.
///
/// A scaffold can show at most one snack bar at a time. If this function is
/// called while another snack bar is already visible, the given snack bar
/// will be added to a queue and displayed after the earlier snack bars have
/// closed.
///
/// To control how long a [SnackBar] remains visible, use [SnackBar.duration].
///
/// To remove the [SnackBar] with an exit animation, use [hideCurrentSnackBar]
/// or call [ScaffoldFeatureController.close] on the returned
/// [ScaffoldFeatureController]. To remove a [SnackBar] suddenly (without an
/// animation), use [removeCurrentSnackBar].
///
/// See [ScaffoldMessenger.of] for information about how to obtain the
/// [ScaffoldMessengerState].
///
/// {@tool dartpad}
/// Here is an example of showing a [SnackBar] when the user presses a button.
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_messenger_state.show_snack_bar.0.dart **
/// {@end-tool}
///
/// ## Relative positioning of floating SnackBars
///
/// A [SnackBar] with [SnackBar.behavior] set to [SnackBarBehavior.floating] is
/// positioned above the widgets provided to [Scaffold.floatingActionButton],
/// [Scaffold.persistentFooterButtons], and [Scaffold.bottomNavigationBar].
/// If some or all of these widgets take up enough space such that the SnackBar
/// would not be visible when positioned above them, an error will be thrown.
/// In this case, consider constraining the size of these widgets to allow room for
/// the SnackBar to be visible.
///
/// {@tool dartpad}
/// Here is an example showing how to display a [SnackBar] with [showSnackBar]
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_messenger_state.show_snack_bar.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// Here is an example showing that a floating [SnackBar] appears above [Scaffold.floatingActionButton].
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_messenger_state.show_snack_bar.1.dart **
/// {@end-tool}
///
/// If [AnimationStyle.duration] is provided in the [snackBarAnimationStyle]
/// parameter, it will be used to override the snackbar show animation duration.
/// Otherwise, defaults to 250ms.
///
/// If [AnimationStyle.reverseDuration] is provided in the [snackBarAnimationStyle]
/// parameter, it will be used to override the snackbar hide animation duration.
/// Otherwise, defaults to 250ms.
///
/// To disable the snackbar animation, use [AnimationStyle.noAnimation].
///
/// {@tool dartpad}
/// This sample showcases how to override [SnackBar] show and hide animation
/// duration using [AnimationStyle] in [ScaffoldMessengerState.showSnackBar].
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_messenger_state.show_snack_bar.2.dart **
/// {@end-tool}
///
ScaffoldFeatureController<SnackBar, SnackBarClosedReason> showSnackBar(
SnackBar snackBar,
{ AnimationStyle? snackBarAnimationStyle }
) {
assert(
_scaffolds.isNotEmpty,
'ScaffoldMessenger.showSnackBar was called, but there are currently no '
'descendant Scaffolds to present to.',
);
_didUpdateAnimationStyle(snackBarAnimationStyle);
_snackBarController ??= SnackBar.createAnimationController(
duration: snackBarAnimationStyle?.duration,
reverseDuration: snackBarAnimationStyle?.reverseDuration,
vsync: this,
)
..addStatusListener(_handleSnackBarStatusChanged);
if (_snackBars.isEmpty) {
assert(_snackBarController!.isDismissed);
_snackBarController!.forward();
}
late ScaffoldFeatureController<SnackBar, SnackBarClosedReason> controller;
controller = ScaffoldFeatureController<SnackBar, SnackBarClosedReason>._(
// We provide a fallback key so that if back-to-back snackbars happen to
// match in structure, material ink splashes and highlights don't survive
// from one to the next.
snackBar.withAnimation(_snackBarController!, fallbackKey: UniqueKey()),
Completer<SnackBarClosedReason>(),
() {
assert(_snackBars.first == controller);
hideCurrentSnackBar();
},
null, // SnackBar doesn't use a builder function so setState() wouldn't rebuild it
);
try {
setState(() {
_snackBars.addLast(controller);
});
_updateScaffolds();
} catch (exception) {
assert (() {
if (exception is FlutterError) {
final String summary = exception.diagnostics.first.toDescription();
if (summary == 'setState() or markNeedsBuild() called during build.') {
final List<DiagnosticsNode> information = <DiagnosticsNode>[
ErrorSummary('The showSnackBar() method cannot be called during build.'),
ErrorDescription(
'The showSnackBar() method was called during build, which is '
'prohibited as showing snack bars requires updating state. Updating '
'state is not possible during build.',
),
ErrorHint(
'Instead of calling showSnackBar() during build, call it directly '
'in your on tap (and related) callbacks. If you need to immediately '
'show a snack bar, make the call in initState() or '
'didChangeDependencies() instead. Otherwise, you can also schedule a '
'post-frame callback using SchedulerBinding.addPostFrameCallback to '
'show the snack bar after the current frame.',
),
context.describeOwnershipChain(
'The ownership chain for the particular ScaffoldMessenger is',
),
];
throw FlutterError.fromParts(information);
}
}
return true;
}());
rethrow;
}
return controller;
}
void _didUpdateAnimationStyle(AnimationStyle? snackBarAnimationStyle) {
if (snackBarAnimationStyle != null) {
if (_snackBarController?.duration != snackBarAnimationStyle.duration ||
_snackBarController?.reverseDuration != snackBarAnimationStyle.reverseDuration) {
_snackBarController?.dispose();
_snackBarController = null;
}
}
}
void _handleSnackBarStatusChanged(AnimationStatus status) {
switch (status) {
case AnimationStatus.dismissed:
assert(_snackBars.isNotEmpty);
setState(() {
_snackBars.removeFirst();
});
_updateScaffolds();
if (_snackBars.isNotEmpty) {
_snackBarController!.forward();
}
case AnimationStatus.completed:
setState(() {
assert(_snackBarTimer == null);
// build will create a new timer if necessary to dismiss the snackBar.
});
_updateScaffolds();
case AnimationStatus.forward:
break;
case AnimationStatus.reverse:
break;
}
}
/// Removes the current [SnackBar] (if any) immediately from registered
/// [Scaffold]s.
///
/// The removed snack bar does not run its normal exit animation. If there are
/// any queued snack bars, they begin their entrance animation immediately.
void removeCurrentSnackBar({ SnackBarClosedReason reason = SnackBarClosedReason.remove }) {
if (_snackBars.isEmpty) {
return;
}
final Completer<SnackBarClosedReason> completer = _snackBars.first._completer;
if (!completer.isCompleted) {
completer.complete(reason);
}
_snackBarTimer?.cancel();
_snackBarTimer = null;
// This will trigger the animation's status callback.
_snackBarController!.value = 0.0;
}
/// Removes the current [SnackBar] by running its normal exit animation.
///
/// The closed completer is called after the animation is complete.
void hideCurrentSnackBar({ SnackBarClosedReason reason = SnackBarClosedReason.hide }) {
if (_snackBars.isEmpty || _snackBarController!.status == AnimationStatus.dismissed) {
return;
}
final Completer<SnackBarClosedReason> completer = _snackBars.first._completer;
if (_accessibleNavigation!) {
_snackBarController!.value = 0.0;
completer.complete(reason);
} else {
_snackBarController!.reverse().then<void>((void value) {
assert(mounted);
if (!completer.isCompleted) {
completer.complete(reason);
}
});
}
_snackBarTimer?.cancel();
_snackBarTimer = null;
}
/// Removes all the snackBars currently in queue by clearing the queue
/// and running normal exit animation on the current snackBar.
void clearSnackBars() {
if (_snackBars.isEmpty || _snackBarController!.status == AnimationStatus.dismissed) {
return;
}
final ScaffoldFeatureController<SnackBar, SnackBarClosedReason> currentSnackbar = _snackBars.first;
_snackBars.clear();
_snackBars.add(currentSnackbar);
hideCurrentSnackBar();
}
// MATERIAL BANNER API
/// Shows a [MaterialBanner] across all registered [Scaffold]s. Scaffolds register
/// to receive material banners from their closest [ScaffoldMessenger] ancestor.
/// If there are several registered scaffolds the material banner is shown
/// simultaneously on all of them.
///
/// A scaffold can show at most one material banner at a time. If this function is
/// called while another material banner is already visible, the given material banner
/// will be added to a queue and displayed after the earlier material banners have
/// closed.
///
/// To remove the [MaterialBanner] with an exit animation, use [hideCurrentMaterialBanner]
/// or call [ScaffoldFeatureController.close] on the returned
/// [ScaffoldFeatureController]. To remove a [MaterialBanner] suddenly (without an
/// animation), use [removeCurrentMaterialBanner].
///
/// See [ScaffoldMessenger.of] for information about how to obtain the
/// [ScaffoldMessengerState].
///
/// {@tool dartpad}
/// Here is an example of showing a [MaterialBanner] when the user presses a button.
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_messenger_state.show_material_banner.0.dart **
/// {@end-tool}
ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason> showMaterialBanner(MaterialBanner materialBanner) {
assert(
_scaffolds.isNotEmpty,
'ScaffoldMessenger.showMaterialBanner was called, but there are currently no '
'descendant Scaffolds to present to.',
);
_materialBannerController ??= MaterialBanner.createAnimationController(vsync: this)
..addStatusListener(_handleMaterialBannerStatusChanged);
if (_materialBanners.isEmpty) {
assert(_materialBannerController!.isDismissed);
_materialBannerController!.forward();
}
late ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason> controller;
controller = ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>._(
// We provide a fallback key so that if back-to-back material banners happen to
// match in structure, material ink splashes and highlights don't survive
// from one to the next.
materialBanner.withAnimation(_materialBannerController!, fallbackKey: UniqueKey()),
Completer<MaterialBannerClosedReason>(),
() {
assert(_materialBanners.first == controller);
hideCurrentMaterialBanner();
},
null, // MaterialBanner doesn't use a builder function so setState() wouldn't rebuild it
);
setState(() {
_materialBanners.addLast(controller);
});
_updateScaffolds();
return controller;
}
void _handleMaterialBannerStatusChanged(AnimationStatus status) {
switch (status) {
case AnimationStatus.dismissed:
assert(_materialBanners.isNotEmpty);
setState(() {
_materialBanners.removeFirst();
});
_updateScaffolds();
if (_materialBanners.isNotEmpty) {
_materialBannerController!.forward();
}
case AnimationStatus.completed:
_updateScaffolds();
case AnimationStatus.forward:
break;
case AnimationStatus.reverse:
break;
}
}
/// Removes the current [MaterialBanner] (if any) immediately from registered
/// [Scaffold]s.
///
/// The removed material banner does not run its normal exit animation. If there are
/// any queued material banners, they begin their entrance animation immediately.
void removeCurrentMaterialBanner({ MaterialBannerClosedReason reason = MaterialBannerClosedReason.remove }) {
if (_materialBanners.isEmpty) {
return;
}
final Completer<MaterialBannerClosedReason> completer = _materialBanners.first._completer;
if (!completer.isCompleted) {
completer.complete(reason);
}
// This will trigger the animation's status callback.
_materialBannerController!.value = 0.0;
}
/// Removes the current [MaterialBanner] by running its normal exit animation.
///
/// The closed completer is called after the animation is complete.
void hideCurrentMaterialBanner({ MaterialBannerClosedReason reason = MaterialBannerClosedReason.hide }) {
if (_materialBanners.isEmpty || _materialBannerController!.status == AnimationStatus.dismissed) {
return;
}
final Completer<MaterialBannerClosedReason> completer = _materialBanners.first._completer;
if (_accessibleNavigation!) {
_materialBannerController!.value = 0.0;
completer.complete(reason);
} else {
_materialBannerController!.reverse().then<void>((void value) {
assert(mounted);
if (!completer.isCompleted) {
completer.complete(reason);
}
});
}
}
/// Removes all the [MaterialBanner]s currently in queue by clearing the queue
/// and running normal exit animation on the current [MaterialBanner].
void clearMaterialBanners() {
if (_materialBanners.isEmpty || _materialBannerController!.status == AnimationStatus.dismissed) {
return;
}
final ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason> currentMaterialBanner = _materialBanners.first;
_materialBanners.clear();
_materialBanners.add(currentMaterialBanner);
hideCurrentMaterialBanner();
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context));
_accessibleNavigation = MediaQuery.accessibleNavigationOf(context);
if (_snackBars.isNotEmpty) {
final ModalRoute<dynamic>? route = ModalRoute.of(context);
if (route == null || route.isCurrent) {
if (_snackBarController!.isCompleted && _snackBarTimer == null) {
final SnackBar snackBar = _snackBars.first._widget;
_snackBarTimer = Timer(snackBar.duration, () {
assert(
_snackBarController!.status == AnimationStatus.forward ||
_snackBarController!.status == AnimationStatus.completed,
);
// Look up MediaQuery again in case the setting changed.
if (snackBar.action != null && MediaQuery.accessibleNavigationOf(context)) {
return;
}
hideCurrentSnackBar(reason: SnackBarClosedReason.timeout);
});
}
}
}
return _ScaffoldMessengerScope(
scaffoldMessengerState: this,
child: widget.child,
);
}
@override
void dispose() {
_materialBannerController?.dispose();
_snackBarController?.dispose();
_snackBarTimer?.cancel();
_snackBarTimer = null;
super.dispose();
}
}
class _ScaffoldMessengerScope extends InheritedWidget {
const _ScaffoldMessengerScope({
required super.child,
required ScaffoldMessengerState scaffoldMessengerState,
}) : _scaffoldMessengerState = scaffoldMessengerState;
final ScaffoldMessengerState _scaffoldMessengerState;
@override
bool updateShouldNotify(_ScaffoldMessengerScope old) => _scaffoldMessengerState != old._scaffoldMessengerState;
}
/// The geometry of the [Scaffold] after all its contents have been laid out
/// except the [FloatingActionButton].
///
/// The [Scaffold] passes this pre-layout geometry to its
/// [FloatingActionButtonLocation], which produces an [Offset] that the
/// [Scaffold] uses to position the [FloatingActionButton].
///
/// For a description of the [Scaffold]'s geometry after it has
/// finished laying out, see the [ScaffoldGeometry].
@immutable
class ScaffoldPrelayoutGeometry {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const ScaffoldPrelayoutGeometry({
required this.bottomSheetSize,
required this.contentBottom,
required this.contentTop,
required this.floatingActionButtonSize,
required this.minInsets,
required this.minViewPadding,
required this.scaffoldSize,
required this.snackBarSize,
required this.materialBannerSize,
required this.textDirection,
});
/// The [Size] of [Scaffold.floatingActionButton].
///
/// If [Scaffold.floatingActionButton] is null, this will be [Size.zero].
final Size floatingActionButtonSize;
/// The [Size] of the [Scaffold]'s [BottomSheet].
///
/// If the [Scaffold] is not currently showing a [BottomSheet],
/// this will be [Size.zero].
final Size bottomSheetSize;
/// The vertical distance from the Scaffold's origin to the bottom of
/// [Scaffold.body].
///
/// This is useful in a [FloatingActionButtonLocation] designed to
/// place the [FloatingActionButton] at the bottom of the screen, while
/// keeping it above the [BottomSheet], the [Scaffold.bottomNavigationBar],
/// or the keyboard.
///
/// The [Scaffold.body] is laid out with respect to [minInsets] already. This
/// means that a [FloatingActionButtonLocation] does not need to factor in
/// [EdgeInsets.bottom] of [minInsets] when aligning a [FloatingActionButton]
/// to [contentBottom].
final double contentBottom;
/// The vertical distance from the [Scaffold]'s origin to the top of
/// [Scaffold.body].
///
/// This is useful in a [FloatingActionButtonLocation] designed to
/// place the [FloatingActionButton] at the top of the screen, while
/// keeping it below the [Scaffold.appBar].
///
/// The [Scaffold.body] is laid out with respect to [minInsets] already. This
/// means that a [FloatingActionButtonLocation] does not need to factor in
/// [EdgeInsets.top] of [minInsets] when aligning a [FloatingActionButton] to
/// [contentTop].
final double contentTop;
/// The minimum padding to inset the [FloatingActionButton] by for it
/// to remain visible.
///
/// This value is the result of calling [MediaQueryData.padding] in the
/// [Scaffold]'s [BuildContext],
/// and is useful for insetting the [FloatingActionButton] to avoid features like
/// the system status bar or the keyboard.
///
/// If [Scaffold.resizeToAvoidBottomInset] is set to false,
/// [EdgeInsets.bottom] of [minInsets] will be 0.0.
final EdgeInsets minInsets;
/// The minimum padding to inset interactive elements to be within a safe,
/// un-obscured space.
///
/// This value reflects the [MediaQueryData.viewPadding] of the [Scaffold]'s
/// [BuildContext] when [Scaffold.resizeToAvoidBottomInset] is false or and
/// the [MediaQueryData.viewInsets] > 0.0. This helps distinguish between
/// different types of obstructions on the screen, such as software keyboards
/// and physical device notches.
final EdgeInsets minViewPadding;
/// The [Size] of the whole [Scaffold].
///
/// If the [Size] of the [Scaffold]'s contents is modified by values such as
/// [Scaffold.resizeToAvoidBottomInset] or the keyboard opening, then the
/// [scaffoldSize] will not reflect those changes.
///
/// This means that [FloatingActionButtonLocation]s designed to reposition
/// the [FloatingActionButton] based on events such as the keyboard popping
/// up should use [minInsets] to make sure that the [FloatingActionButton] is
/// inset by enough to remain visible.
///
/// See [minInsets] and [MediaQueryData.padding] for more information on the
/// appropriate insets to apply.
final Size scaffoldSize;
/// The [Size] of the [Scaffold]'s [SnackBar].
///
/// If the [Scaffold] is not showing a [SnackBar], this will be [Size.zero].
final Size snackBarSize;
/// The [Size] of the [Scaffold]'s [MaterialBanner].
///
/// If the [Scaffold] is not showing a [MaterialBanner], this will be [Size.zero].
final Size materialBannerSize;
/// The [TextDirection] of the [Scaffold]'s [BuildContext].
final TextDirection textDirection;
}
/// A snapshot of a transition between two [FloatingActionButtonLocation]s.
///
/// [ScaffoldState] uses this to seamlessly change transition animations
/// when a running [FloatingActionButtonLocation] transition is interrupted by a new transition.
@immutable
class _TransitionSnapshotFabLocation extends FloatingActionButtonLocation {
const _TransitionSnapshotFabLocation(this.begin, this.end, this.animator, this.progress);
final FloatingActionButtonLocation begin;
final FloatingActionButtonLocation end;
final FloatingActionButtonAnimator animator;
final double progress;
@override
Offset getOffset(ScaffoldPrelayoutGeometry scaffoldGeometry) {
return animator.getOffset(
begin: begin.getOffset(scaffoldGeometry),
end: end.getOffset(scaffoldGeometry),
progress: progress,
);
}
@override
String toString() {
return '${objectRuntimeType(this, '_TransitionSnapshotFabLocation')}(begin: $begin, end: $end, progress: $progress)';
}
}
/// Geometry information for [Scaffold] components after layout is finished.
///
/// To get a [ValueNotifier] for the scaffold geometry of a given
/// [BuildContext], use [Scaffold.geometryOf].
///
/// The ScaffoldGeometry is only available during the paint phase, because
/// its value is computed during the animation and layout phases prior to painting.
///
/// For an example of using the [ScaffoldGeometry], see the [BottomAppBar],
/// which uses the [ScaffoldGeometry] to paint a notch around the
/// [FloatingActionButton].
///
/// For information about the [Scaffold]'s geometry that is used while laying
/// out the [FloatingActionButton], see [ScaffoldPrelayoutGeometry].
@immutable
class ScaffoldGeometry {
/// Create an object that describes the geometry of a [Scaffold].
const ScaffoldGeometry({
this.bottomNavigationBarTop,
this.floatingActionButtonArea,
});
/// The distance from the [Scaffold]'s top edge to the top edge of the
/// rectangle in which the [Scaffold.bottomNavigationBar] bar is laid out.
///
/// Null if [Scaffold.bottomNavigationBar] is null.
final double? bottomNavigationBarTop;
/// The [Scaffold.floatingActionButton]'s bounding rectangle.
///
/// This is null when there is no floating action button showing.
final Rect? floatingActionButtonArea;
ScaffoldGeometry _scaleFloatingActionButton(double scaleFactor) {
if (scaleFactor == 1.0) {
return this;
}
if (scaleFactor == 0.0) {
return ScaffoldGeometry(
bottomNavigationBarTop: bottomNavigationBarTop,
);
}
final Rect scaledButton = Rect.lerp(
floatingActionButtonArea!.center & Size.zero,
floatingActionButtonArea,
scaleFactor,
)!;
return copyWith(floatingActionButtonArea: scaledButton);
}
/// Creates a copy of this [ScaffoldGeometry] but with the given fields replaced with
/// the new values.
ScaffoldGeometry copyWith({
double? bottomNavigationBarTop,
Rect? floatingActionButtonArea,
}) {
return ScaffoldGeometry(
bottomNavigationBarTop: bottomNavigationBarTop ?? this.bottomNavigationBarTop,
floatingActionButtonArea: floatingActionButtonArea ?? this.floatingActionButtonArea,
);
}
}
class _ScaffoldGeometryNotifier extends ChangeNotifier implements ValueListenable<ScaffoldGeometry> {
_ScaffoldGeometryNotifier(this.geometry, this.context);
final BuildContext context;
double? floatingActionButtonScale;
ScaffoldGeometry geometry;
@override
ScaffoldGeometry get value {
assert(() {
final RenderObject? renderObject = context.findRenderObject();
if (renderObject == null || !renderObject.owner!.debugDoingPaint) {
throw FlutterError(
'Scaffold.geometryOf() must only be accessed during the paint phase.\n'
'The ScaffoldGeometry is only available during the paint phase, because '
'its value is computed during the animation and layout phases prior to painting.',
);
}
return true;
}());
return geometry._scaleFloatingActionButton(floatingActionButtonScale!);
}
void _updateWith({
double? bottomNavigationBarTop,
Rect? floatingActionButtonArea,
double? floatingActionButtonScale,
}) {
this.floatingActionButtonScale = floatingActionButtonScale ?? this.floatingActionButtonScale;
geometry = geometry.copyWith(
bottomNavigationBarTop: bottomNavigationBarTop,
floatingActionButtonArea: floatingActionButtonArea,
);
notifyListeners();
}
}
// Used to communicate the height of the Scaffold's bottomNavigationBar and
// persistentFooterButtons to the LayoutBuilder which builds the Scaffold's body.
//
// Scaffold expects a _BodyBoxConstraints to be passed to the _BodyBuilder
// widget's LayoutBuilder, see _ScaffoldLayout.performLayout(). The BoxConstraints
// methods that construct new BoxConstraints objects, like copyWith() have not
// been overridden here because we expect the _BodyBoxConstraintsObject to be
// passed along unmodified to the LayoutBuilder. If that changes in the future
// then _BodyBuilder will assert.
class _BodyBoxConstraints extends BoxConstraints {
const _BodyBoxConstraints({
super.maxWidth,
super.maxHeight,
required this.bottomWidgetsHeight,
required this.appBarHeight,
required this.materialBannerHeight,
}) : assert(bottomWidgetsHeight >= 0),
assert(appBarHeight >= 0),
assert(materialBannerHeight >= 0);
final double bottomWidgetsHeight;
final double appBarHeight;
final double materialBannerHeight;
// RenderObject.layout() will only short-circuit its call to its performLayout
// method if the new layout constraints are not == to the current constraints.
// If the height of the bottom widgets has changed, even though the constraints'
// min and max values have not, we still want performLayout to happen.
@override
bool operator ==(Object other) {
if (super != other) {
return false;
}
return other is _BodyBoxConstraints
&& other.materialBannerHeight == materialBannerHeight
&& other.bottomWidgetsHeight == bottomWidgetsHeight
&& other.appBarHeight == appBarHeight;
}
@override
int get hashCode => Object.hash(super.hashCode, materialBannerHeight, bottomWidgetsHeight, appBarHeight);
}
// Used when Scaffold.extendBody is true to wrap the scaffold's body in a MediaQuery
// whose padding accounts for the height of the bottomNavigationBar and/or the
// persistentFooterButtons.
//
// The bottom widgets' height is passed along via the _BodyBoxConstraints parameter.
// The constraints parameter is constructed in_ScaffoldLayout.performLayout().
class _BodyBuilder extends StatelessWidget {
const _BodyBuilder({
required this.extendBody,
required this.extendBodyBehindAppBar,
required this.body,
});
final Widget body;
final bool extendBody;
final bool extendBodyBehindAppBar;
@override
Widget build(BuildContext context) {
if (!extendBody && !extendBodyBehindAppBar) {
return body;
}
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final _BodyBoxConstraints bodyConstraints = constraints as _BodyBoxConstraints;
final MediaQueryData metrics = MediaQuery.of(context);
final double bottom = extendBody
? math.max(metrics.padding.bottom, bodyConstraints.bottomWidgetsHeight)
: metrics.padding.bottom;
final double top = extendBodyBehindAppBar
? math.max(metrics.padding.top,
bodyConstraints.appBarHeight + bodyConstraints.materialBannerHeight)
: metrics.padding.top;
return MediaQuery(
data: metrics.copyWith(
padding: metrics.padding.copyWith(
top: top,
bottom: bottom,
),
),
child: body,
);
},
);
}
}
class _ScaffoldLayout extends MultiChildLayoutDelegate {
_ScaffoldLayout({
required this.minInsets,
required this.minViewPadding,
required this.textDirection,
required this.geometryNotifier,
// for floating action button
required this.previousFloatingActionButtonLocation,
required this.currentFloatingActionButtonLocation,
required this.floatingActionButtonMoveAnimationProgress,