Skip to main content

waft_material/
scaffold.rs

1//! Flutter counterpart: material_ui's `scaffold.dart`.
2//!
3//! `_BodyBoxConstraints` and `_BottomSheetBoxConstraints` are `BoxConstraints` subclass
4//! instances ([`AnyBoxConstraints`]). They reach the body's and the sheet's `LayoutBuilder`
5//! only because nothing but `LayoutId` and `MediaQuery` sits between the scaffold's layout and
6//! those builders: a render object in between would hand on the plain value, and the builders'
7//! casts would panic.
8
9use std::any::Any;
10use std::cell::Cell;
11use std::collections::{HashMap, HashSet, VecDeque};
12use std::fmt::{self, Debug};
13use std::marker::PhantomData;
14use std::rc::{Rc, Weak};
15use std::time::Duration;
16
17use waft_animation::{
18    Animatable, Animation, AnimationController, AnimationMin, AnimationRef, AnimationStatus,
19    AnimationStatusListener, AnimationStyle, AnyAnimation, Curve, CurveTween, CurvedAnimation,
20    Curves, Drive, Interval, Split, TrainHoppingAnimation, Tween,
21};
22use waft_embedder::{Clip, Color, Offset, Rect, Size, TargetPlatform, TextDirection, clamp_double};
23use waft_foundation::{
24    App, ChangeNotifier, ChangeNotifierData, Completer, CompleterFuture, Handle, Listenable,
25    Listener, OptionRetained, PRECISION_ERROR_TOLERANCE, Ref, Timer, UniqueKey, ValueKey,
26    VoidCallback,
27};
28use waft_gestures::{DragEndDetails, DragStartDetails, GestureBinding, HitTestResult};
29use waft_painting::{
30    AlignmentDirectional, AlignmentGeometry, Border, BoxDecoration, EdgeInsets, EdgeInsetsGeometry,
31    ShapeBorderRef,
32};
33use waft_rendering::{
34    AnyBoxConstraints, BoxConstraints, BoxConstraintsExtension, BoxHitTestEntry, ChildLayoutId,
35    HitTestBehavior, MultiChildLayoutChildren, MultiChildLayoutDelegate,
36};
37use waft_scheduler::{Ticker, TickerCallback, TickerFuture, TickerProviderObject};
38use waft_widgets::{
39    Action, ActionData, Actions, Align, AnyModalRoute, BuildContext, Builder, ConstrainedBox,
40    Container, CustomMultiChildLayout, DismissAction, DismissIntent, DraggableScrollableActuator,
41    DraggableScrollableNotification, FadeTransition, GlobalKey, InheritedModel, InheritedModelKind,
42    InheritedWidget, IntoWidget, IntrinsicHeight, KeyRef, KeyedSubtree, LayoutBuilder, LayoutId,
43    ListenableBuilder, LocalHistoryEntry, MediaQuery, MetaData, ModalBarrier, NotificationListener,
44    OverflowBar, OverflowBarAlignment, Padding, PreferredSizeWidgetRef, PrimaryScrollController,
45    RestorableBool, RestorableProperty, RestorableValue, RestorationBucket, RestorationMixin,
46    RestorationMixinData, RotationTransition, SafeArea, ScaleTransition,
47    ScrollNotificationObserver, Semantics, SizedBox, Stack, State, StateData, StateSetter,
48    StatefulBuilder, StatefulBuilderState, StatefulWidget, StatelessWidget,
49    TickerProviderStateMixin, TickerProviderStateMixinData, View, Widget, WidgetBuilder, WidgetRef,
50    WidgetsBinding, WidgetsBindingObserverObject, WidgetsBindingObserverRef, downcast_widget,
51};
52
53use crate::app_bar::AppBar;
54use crate::banner::{MaterialBanner, MaterialBannerClosedReason};
55use crate::banner_theme::MaterialBannerTheme;
56use crate::bottom_sheet::BottomSheet;
57use crate::colors::Colors;
58#[expect(
59    deprecated,
60    reason = "Dart's `_standardBottomSheetCurve` is the deprecated `standardEasing`"
61)]
62use crate::curves::standard_easing;
63use crate::divider::Divider;
64use crate::drawer::{DrawerAlignment, DrawerCallback, DrawerController, DrawerControllerState};
65use crate::flexible_space_bar::FlexibleSpaceBar;
66use crate::floating_action_button::FloatingActionButton;
67use crate::floating_action_button_location::{
68    FloatingActionButtonAnimator, FloatingActionButtonAnimatorRef, FloatingActionButtonLocation,
69    FloatingActionButtonLocationRef, K_FLOATING_ACTION_BUTTON_SEGUE,
70    K_FLOATING_ACTION_BUTTON_TURN_INTERVAL,
71};
72use crate::material::Material;
73use crate::snack_bar::{SnackBar, SnackBarClosedReason};
74use crate::snack_bar_theme::{SnackBarBehavior, SnackBarTheme};
75use crate::theme::Theme;
76
77/// Dart's `_kDefaultFloatingActionButtonLocation`.
78fn default_floating_action_button_location() -> FloatingActionButtonLocationRef {
79    <dyn FloatingActionButtonLocation>::end_float()
80}
81
82/// Dart's `_kDefaultFloatingActionButtonAnimator`.
83fn default_floating_action_button_animator() -> FloatingActionButtonAnimatorRef {
84    <dyn FloatingActionButtonAnimator>::scaling()
85}
86
87/// Dart's `_standardBottomSheetCurve`.
88#[expect(
89    deprecated,
90    reason = "Dart's `_standardBottomSheetCurve` is the deprecated `standardEasing`"
91)]
92fn standard_bottom_sheet_curve() -> Rc<dyn Curve> {
93    standard_easing()
94}
95
96// When the top of the BottomSheet crosses this threshold, it will start to
97// shrink the FAB and show a scrim.
98const K_BOTTOM_SHEET_DOMINATES_PERCENTAGE: f64 = 0.3;
99const K_MIN_BOTTOM_SHEET_SCRIM_OPACITY: f64 = 0.1;
100const K_MAX_BOTTOM_SHEET_SCRIM_OPACITY: f64 = 0.6;
101
102/// Dart's `_ScaffoldSlot`.
103#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
104enum ScaffoldSlot {
105    Body,
106    AppBar,
107    BodyScrim,
108    BottomSheet,
109    SnackBar,
110    MaterialBanner,
111    PersistentFooter,
112    BottomNavigationBar,
113    FloatingActionButton,
114    Drawer,
115    EndDrawer,
116    StatusBar,
117}
118
119impl ScaffoldSlot {
120    /// The [`ChildLayoutId`] this slot is known by, Dart's enum value as the `LayoutId.id`.
121    fn id(self) -> ChildLayoutId {
122        Rc::new(ValueKey::new(self))
123    }
124}
125
126/// Manages [`SnackBar`]s and [`MaterialBanner`]s for descendant [`Scaffold`]s.
127///
128/// This class provides APIs for showing snack bars and material banners at the
129/// bottom and top of the screen, respectively.
130///
131/// To display one of these notifications, obtain the [`ScaffoldMessengerState`]
132/// for the current [`BuildContext`] via [`ScaffoldMessenger::of`] and use the
133/// [`ScaffoldMessengerState::show_snack_bar`] or the
134/// [`ScaffoldMessengerState::show_material_banner`] functions.
135///
136/// When the [`ScaffoldMessenger`] has nested [`Scaffold`] descendants, the
137/// ScaffoldMessenger will only present the notification to the root Scaffold of
138/// the subtree of Scaffolds. In order to show notifications for the inner, nested
139/// Scaffolds, set a new scope by instantiating a new ScaffoldMessenger in
140/// between the levels of nesting.
141///
142/// See also:
143///
144///  * [`SnackBar`], which is a temporary notification typically shown near the
145///    bottom of the app using the [`ScaffoldMessengerState::show_snack_bar`] method.
146///  * [`MaterialBanner`], which is a temporary notification typically shown at the
147///    top of the app using the [`ScaffoldMessengerState::show_material_banner`] method.
148///  * [`debug_check_has_scaffold_messenger`](crate::debug_check_has_scaffold_messenger),
149///    which asserts that the given context has a [`ScaffoldMessenger`] ancestor.
150#[derive(Debug)]
151pub struct ScaffoldMessenger {
152    pub key: Option<KeyRef>,
153
154    /// The widget below this widget in the tree.
155    pub child: WidgetRef,
156}
157
158impl ScaffoldMessenger {
159    /// Creates a widget that manages [`SnackBar`]s for [`Scaffold`] descendants.
160    #[cfg_attr(debug_assertions, track_caller)]
161    pub fn new<K>(child: impl IntoWidget<K>) -> ScaffoldMessenger {
162        ScaffoldMessenger {
163            key: None,
164            child: child.into_widget(),
165        }
166    }
167
168    /// Dart `ScaffoldMessenger(key:)`.
169    pub fn key(mut self, key: KeyRef) -> ScaffoldMessenger {
170        self.key = Some(key);
171        self
172    }
173
174    /// The state from the closest instance of this class that encloses the given
175    /// context.
176    ///
177    /// Typical usage of the [`ScaffoldMessenger::of`] function is to call it in
178    /// response to a user gesture or an application state change.
179    ///
180    /// A less elegant but more expedient solution is to assign a [`GlobalKey`] to the
181    /// [`ScaffoldMessenger`], then use the `key.current_state` method to obtain the
182    /// [`ScaffoldMessengerState`] rather than using the [`ScaffoldMessenger::of`]
183    /// function. The `MaterialApp.scaffoldMessengerKey` refers to the root
184    /// ScaffoldMessenger that is provided by default.
185    ///
186    /// If there is no [`ScaffoldMessenger`] in scope, then this will assert in
187    /// debug mode, and throw an exception in release mode.
188    ///
189    /// See also:
190    ///
191    ///  * [`maybe_of`](Self::maybe_of), which is a similar function but will return `None`
192    ///    instead of throwing if there is no [`ScaffoldMessenger`] ancestor.
193    ///  * [`debug_check_has_scaffold_messenger`](crate::debug_check_has_scaffold_messenger),
194    ///    which asserts that the given context has a [`ScaffoldMessenger`] ancestor.
195    pub fn of(app: &mut App, context: BuildContext) -> Handle<ScaffoldMessengerState> {
196        debug_assert!(crate::debug::debug_check_has_scaffold_messenger(
197            app, context
198        ));
199
200        let scope = context
201            .depend_on_inherited_widget_of_exact_type::<ScaffoldMessengerScope>(app)
202            .expect("checked by debug_check_has_scaffold_messenger");
203        scope.scaffold_messenger_state
204    }
205
206    /// The state from the closest instance of this class that encloses the given
207    /// context, if any.
208    ///
209    /// Will return `None` if a [`ScaffoldMessenger`] is not found in the given context.
210    ///
211    /// See also:
212    ///
213    ///  * [`of`](Self::of), which is a similar function, except that it will throw an
214    ///    exception if a [`ScaffoldMessenger`] is not found in the given context.
215    pub fn maybe_of(
216        app: &mut App,
217        context: BuildContext,
218    ) -> Option<Handle<ScaffoldMessengerState>> {
219        let scope = context.depend_on_inherited_widget_of_exact_type::<ScaffoldMessengerScope>(app);
220        scope.map(|scope| scope.scaffold_messenger_state)
221    }
222}
223
224impl StatefulWidget for ScaffoldMessenger {
225    type State = ScaffoldMessengerState;
226
227    fn key(&self) -> Option<&KeyRef> {
228        self.key.as_ref()
229    }
230
231    fn create_state(&self) -> ScaffoldMessengerState {
232        ScaffoldMessengerState {
233            state: StateData::new(),
234            ticker_provider: TickerProviderStateMixinData::new(),
235            scaffolds: Vec::new(),
236            material_banners: VecDeque::new(),
237            material_banner_controller: None,
238            snack_bars: VecDeque::new(),
239            snack_bar_controller: None,
240            snack_bar_timer: None,
241            accessible_navigation: false,
242        }
243    }
244}
245
246/// State for a [`ScaffoldMessenger`].
247///
248/// A [`ScaffoldMessengerState`] object can be used to [`show_snack_bar`](Self::show_snack_bar)
249/// or [`show_material_banner`](Self::show_material_banner) for every registered [`Scaffold`]
250/// that is a descendant of the associated [`ScaffoldMessenger`]. Scaffolds will register to
251/// receive [`SnackBar`]s and [`MaterialBanner`]s from their closest ScaffoldMessenger
252/// ancestor.
253///
254/// Typically obtained via [`ScaffoldMessenger::of`].
255pub struct ScaffoldMessengerState {
256    state: StateData<ScaffoldMessenger>,
257    ticker_provider: TickerProviderStateMixinData,
258    /// Dart's `LinkedHashSet<ScaffoldState>`: insertion order, each scaffold once.
259    scaffolds: Vec<Handle<ScaffoldState>>,
260    material_banners:
261        VecDeque<Rc<ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>>>,
262    material_banner_controller: Option<Ref<AnimationController>>,
263    snack_bars: VecDeque<Rc<ScaffoldFeatureController<SnackBar, SnackBarClosedReason>>>,
264    snack_bar_controller: Option<Ref<AnimationController>>,
265    snack_bar_timer: Option<Timer>,
266    /// Dart's `late bool _accessibleNavigation`, set before the first build.
267    accessible_navigation: bool,
268}
269
270impl ScaffoldMessengerState {
271    fn register(self: Handle<Self>, app: &mut App, scaffold: Handle<ScaffoldState>) {
272        if !app.get(self).scaffolds.contains(&scaffold) {
273            app.get_mut(self).scaffolds.push(scaffold);
274        }
275
276        if self.is_root(app, scaffold) {
277            if !app.get(self).snack_bars.is_empty() {
278                scaffold.update_snack_bar(app);
279            }
280
281            if !app.get(self).material_banners.is_empty() {
282                scaffold.update_material_banner(app);
283            }
284        }
285    }
286
287    fn unregister(self: Handle<Self>, app: &mut App, scaffold: Handle<ScaffoldState>) {
288        let scaffolds = &mut app.get_mut(self).scaffolds;
289        let position = scaffolds
290            .iter()
291            .position(|registered| *registered == scaffold);
292        // ScaffoldStates should only be removed once.
293        debug_assert!(position.is_some());
294        if let Some(position) = position {
295            scaffolds.remove(position);
296        }
297    }
298
299    fn update_scaffolds(self: Handle<Self>, app: &mut App) {
300        let scaffolds = app.get(self).scaffolds.clone();
301        for scaffold in scaffolds {
302            if self.is_root(app, scaffold) {
303                scaffold.update_snack_bar(app);
304                scaffold.update_material_banner(app);
305            }
306        }
307    }
308
309    // Nested Scaffolds are handled by the ScaffoldMessenger by only presenting a
310    // MaterialBanner or SnackBar in the root Scaffold of the nested set.
311    fn is_root(self: Handle<Self>, app: &App, scaffold: Handle<ScaffoldState>) -> bool {
312        let parent = scaffold
313            .context(app)
314            .find_ancestor_state_of_type::<ScaffoldState>(app);
315        match parent {
316            None => true,
317            Some(parent) => !app.get(self).scaffolds.contains(&parent),
318        }
319    }
320
321    // SNACKBAR API
322
323    /// Shows a [`SnackBar`] across all registered [`Scaffold`]s. Scaffolds register
324    /// to receive snack bars from their closest [`ScaffoldMessenger`] ancestor.
325    /// If there are several registered scaffolds the snack bar is shown
326    /// simultaneously on all of them.
327    ///
328    /// A scaffold can show at most one snack bar at a time. If this function is
329    /// called while another snack bar is already visible, the given snack bar
330    /// will be added to a queue and displayed after the earlier snack bars have
331    /// closed.
332    ///
333    /// To control how long a [`SnackBar`] remains visible, use [`SnackBar::duration`].
334    ///
335    /// To remove the [`SnackBar`] with an exit animation, use
336    /// [`hide_current_snack_bar`](Self::hide_current_snack_bar) or call
337    /// [`ScaffoldFeatureController::close`] on the returned [`ScaffoldFeatureController`]. To
338    /// remove a [`SnackBar`] suddenly (without an animation), use
339    /// [`remove_current_snack_bar`](Self::remove_current_snack_bar).
340    ///
341    /// See [`ScaffoldMessenger::of`] for information about how to obtain the
342    /// [`ScaffoldMessengerState`].
343    ///
344    /// ## Relative positioning of floating SnackBars
345    ///
346    /// A [`SnackBar`] with [`SnackBar::behavior`] set to [`SnackBarBehavior::Floating`] is
347    /// positioned above the widgets provided to [`Scaffold::floating_action_button`],
348    /// [`Scaffold::persistent_footer_buttons`], and [`Scaffold::bottom_navigation_bar`].
349    /// If some or all of these widgets take up enough space such that the SnackBar
350    /// would not be visible when positioned above them, an error will be thrown.
351    /// In this case, consider constraining the size of these widgets to allow room for
352    /// the SnackBar to be visible.
353    ///
354    /// If [`AnimationStyle::duration`] is provided in the `snack_bar_animation_style`
355    /// parameter, it will be used to override the snackbar show animation duration.
356    /// Otherwise, defaults to 250ms.
357    ///
358    /// If [`AnimationStyle::reverse_duration`] is provided in the
359    /// `snack_bar_animation_style` parameter, it will be used to override the snackbar hide
360    /// animation duration. Otherwise, defaults to 250ms.
361    ///
362    /// To disable the snackbar animation, use `AnimationStyle::no_animation()`.
363    pub fn show_snack_bar(
364        self: Handle<Self>,
365        app: &mut App,
366        snack_bar: SnackBar,
367        snack_bar_animation_style: Option<AnimationStyle>,
368    ) -> Rc<ScaffoldFeatureController<SnackBar, SnackBarClosedReason>> {
369        debug_assert!(
370            !app.get(self).scaffolds.is_empty(),
371            "ScaffoldMessenger.showSnackBar was called, but there are currently no \
372             descendant Scaffolds to present to."
373        );
374        self.did_update_animation_style(app, snack_bar_animation_style.as_ref());
375        if app.get(self).snack_bar_controller.is_none() {
376            let controller = SnackBar::create_animation_controller(
377                app,
378                self,
379                snack_bar_animation_style
380                    .as_ref()
381                    .and_then(|style| style.duration),
382                snack_bar_animation_style
383                    .as_ref()
384                    .and_then(|style| style.reverse_duration),
385            );
386            controller.add_status_listener(
387                app,
388                AnimationStatusListener::handle_method(
389                    self,
390                    ScaffoldMessengerState::handle_snack_bar_status_changed,
391                ),
392            );
393            app.get_mut(self).snack_bar_controller = Some(controller);
394        }
395        let snack_bar_controller = self.snack_bar_controller(app).handle();
396        if app.get(self).snack_bars.is_empty() {
397            debug_assert!(snack_bar_controller.is_dismissed(app));
398            snack_bar_controller.forward(app, None);
399        }
400        let controller = Rc::new_cyclic(
401            |controller: &std::rc::Weak<
402                ScaffoldFeatureController<SnackBar, SnackBarClosedReason>,
403            >| {
404                let controller = controller.clone();
405                ScaffoldFeatureController::new(
406                    // We provide a fallback key so that if back-to-back snackbars happen to
407                    // match in structure, material ink splashes and highlights don't survive
408                    // from one to the next.
409                    snack_bar.with_animation(
410                        self.snack_bar_controller(app).erase(),
411                        Some(KeyRef::Local(Rc::new(UniqueKey::new()))),
412                    ),
413                    Completer::new(),
414                    Rc::new(move |app: &mut App| {
415                        debug_assert!(
416                            app.get(self)
417                                .snack_bars
418                                .front()
419                                .zip(controller.upgrade())
420                                .is_some_and(|(first, controller)| Rc::ptr_eq(first, &controller))
421                        );
422                        self.hide_current_snack_bar(app, SnackBarClosedReason::Hide);
423                    }),
424                    // SnackBar doesn't use a builder function so setState() wouldn't rebuild it
425                    None,
426                )
427            },
428        );
429        let added = Rc::clone(&controller);
430        let shown = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
431            self.set_state(app, move |state| {
432                state.snack_bars.push_back(added);
433            });
434            self.update_scaffolds(app);
435        }));
436        if let Err(exception) = shown {
437            if cfg!(debug_assertions) && is_set_state_during_build(&*exception) {
438                panic!(
439                    "The showSnackBar() method cannot be called during build.\n\
440                     The showSnackBar() method was called during build, which is prohibited \
441                     as showing snack bars requires updating state. Updating state is not \
442                     possible during build.\n\
443                     Instead of calling showSnackBar() during build, call it directly in your \
444                     on tap (and related) callbacks. If you need to immediately show a snack \
445                     bar, make the call in initState() or didChangeDependencies() instead. \
446                     Otherwise, you can also schedule a post-frame callback using \
447                     SchedulerBinding.addPostFrameCallback to show the snack bar after the \
448                     current frame."
449                );
450            }
451            std::panic::resume_unwind(exception);
452        }
453
454        controller
455    }
456
457    fn did_update_animation_style(
458        self: Handle<Self>,
459        app: &mut App,
460        snack_bar_animation_style: Option<&AnimationStyle>,
461    ) {
462        if let Some(snack_bar_animation_style) = snack_bar_animation_style {
463            let controller = app.get(self).snack_bar_controller.handle();
464            let (duration, reverse_duration) = match controller {
465                Some(controller) => {
466                    let controller = app.get(controller);
467                    (controller.duration, controller.reverse_duration)
468                }
469                None => (None, None),
470            };
471            if duration != snack_bar_animation_style.duration
472                || reverse_duration != snack_bar_animation_style.reverse_duration
473            {
474                if let Some(controller) = controller {
475                    controller.dispose(app);
476                }
477                app.get_mut(self).snack_bar_controller = None;
478            }
479        }
480    }
481
482    fn snack_bar_controller(self: Handle<Self>, app: &App) -> &Ref<AnimationController> {
483        app.get(self)
484            .snack_bar_controller
485            .as_ref()
486            .expect("a snack bar was shown")
487    }
488
489    fn material_banner_controller(self: Handle<Self>, app: &App) -> &Ref<AnimationController> {
490        app.get(self)
491            .material_banner_controller
492            .as_ref()
493            .expect("a material banner was shown")
494    }
495
496    fn handle_snack_bar_status_changed(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
497        match status {
498            AnimationStatus::Dismissed => {
499                debug_assert!(!app.get(self).snack_bars.is_empty());
500                self.set_state(app, |state| {
501                    state.snack_bars.pop_front();
502                });
503                self.update_scaffolds(app);
504                if !app.get(self).snack_bars.is_empty() {
505                    self.snack_bar_controller(app).forward(app, None);
506                }
507            }
508            AnimationStatus::Completed => {
509                self.set_state(app, |state| {
510                    debug_assert!(state.snack_bar_timer.is_none());
511                    // build will create a new timer if necessary to dismiss the snackBar.
512                });
513                self.update_scaffolds(app);
514            }
515            AnimationStatus::Forward | AnimationStatus::Reverse => {}
516        }
517    }
518
519    /// Removes the current [`SnackBar`] (if any) immediately from registered
520    /// [`Scaffold`]s.
521    ///
522    /// The removed snack bar does not run its normal exit animation. If there are
523    /// any queued snack bars, they begin their entrance animation immediately.
524    ///
525    /// Dart's default `reason` is [`SnackBarClosedReason::Remove`].
526    pub fn remove_current_snack_bar(
527        self: Handle<Self>,
528        app: &mut App,
529        reason: SnackBarClosedReason,
530    ) {
531        let Some(first) = app.get(self).snack_bars.front().cloned() else {
532            return;
533        };
534        let completer = first.completer.clone();
535        if !completer.is_completed() {
536            completer.complete(app, reason);
537        }
538        if let Some(timer) = app.get_mut(self).snack_bar_timer.take() {
539            timer.cancel(app);
540        }
541        // This will trigger the animation's status callback.
542        self.snack_bar_controller(app).set_value(app, 0.0);
543    }
544
545    /// Removes the current [`SnackBar`] by running its normal exit animation.
546    ///
547    /// The closed completer is called after the animation is complete.
548    ///
549    /// Dart's default `reason` is [`SnackBarClosedReason::Hide`].
550    pub fn hide_current_snack_bar(self: Handle<Self>, app: &mut App, reason: SnackBarClosedReason) {
551        if app.get(self).snack_bars.is_empty() || self.snack_bar_controller(app).is_dismissed(app) {
552            return;
553        }
554        let completer = app
555            .get(self)
556            .snack_bars
557            .front()
558            .expect("checked above")
559            .completer
560            .clone();
561        let controller = self.snack_bar_controller(app).handle();
562        if app.get(self).accessible_navigation {
563            controller.set_value(app, 0.0);
564            completer.complete(app, reason);
565        } else {
566            controller.reverse(app, None).when_complete(
567                app,
568                Listener::new(move |app| {
569                    debug_assert!(self.mounted(app));
570                    if !completer.is_completed() {
571                        completer.complete(app, reason);
572                    }
573                }),
574            );
575        }
576        if let Some(timer) = app.get_mut(self).snack_bar_timer.take() {
577            timer.cancel(app);
578        }
579    }
580
581    /// Removes all the snackBars currently in queue by clearing the queue
582    /// and running normal exit animation on the current snackBar.
583    pub fn clear_snack_bars(self: Handle<Self>, app: &mut App) {
584        if app.get(self).snack_bars.is_empty() || self.snack_bar_controller(app).is_dismissed(app) {
585            return;
586        }
587        let snack_bars = &mut app.get_mut(self).snack_bars;
588        let current_snackbar = snack_bars.pop_front().expect("checked above");
589        snack_bars.clear();
590        snack_bars.push_back(current_snackbar);
591        self.hide_current_snack_bar(app, SnackBarClosedReason::Hide);
592    }
593
594    // MATERIAL BANNER API
595
596    /// Shows a [`MaterialBanner`] across all registered [`Scaffold`]s. Scaffolds register
597    /// to receive material banners from their closest [`ScaffoldMessenger`] ancestor.
598    /// If there are several registered scaffolds the material banner is shown
599    /// simultaneously on all of them.
600    ///
601    /// A scaffold can show at most one material banner at a time. If this function is
602    /// called while another material banner is already visible, the given material banner
603    /// will be added to a queue and displayed after the earlier material banners have
604    /// closed.
605    ///
606    /// To remove the [`MaterialBanner`] with an exit animation, use
607    /// [`hide_current_material_banner`](Self::hide_current_material_banner) or call
608    /// [`ScaffoldFeatureController::close`] on the returned [`ScaffoldFeatureController`]. To
609    /// remove a [`MaterialBanner`] suddenly (without an animation), use
610    /// [`remove_current_material_banner`](Self::remove_current_material_banner).
611    ///
612    /// When this [`ScaffoldMessenger`] is above the `Navigator`, such as the one
613    /// created by `MaterialApp`, a [`MaterialBanner`] stays visible after the route
614    /// that showed it is popped, and that route's [`BuildContext`] is deactivated.
615    /// Because of this, callbacks in [`MaterialBanner::actions`] should not call
616    /// [`ScaffoldMessenger::of`] with a [`BuildContext`] from the route that showed the
617    /// banner. Instead, wrap the action widget in a [`Builder`] to obtain an active
618    /// [`BuildContext`], or save the [`ScaffoldMessengerState`] reference before calling
619    /// [`show_material_banner`](Self::show_material_banner).
620    ///
621    /// See [`ScaffoldMessenger::of`] for information about how to obtain the
622    /// [`ScaffoldMessengerState`].
623    pub fn show_material_banner(
624        self: Handle<Self>,
625        app: &mut App,
626        material_banner: MaterialBanner,
627    ) -> Rc<ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>> {
628        debug_assert!(
629            !app.get(self).scaffolds.is_empty(),
630            "ScaffoldMessenger.showMaterialBanner was called, but there are currently no \
631             descendant Scaffolds to present to."
632        );
633        if app.get(self).material_banner_controller.is_none() {
634            let controller = MaterialBanner::create_animation_controller(app, self);
635            controller.add_status_listener(
636                app,
637                AnimationStatusListener::handle_method(
638                    self,
639                    ScaffoldMessengerState::handle_material_banner_status_changed,
640                ),
641            );
642            app.get_mut(self).material_banner_controller = Some(controller);
643        }
644        let material_banner_controller = self.material_banner_controller(app).handle();
645        if app.get(self).material_banners.is_empty() {
646            debug_assert!(material_banner_controller.is_dismissed(app));
647            material_banner_controller.forward(app, None);
648        }
649        let controller = Rc::new_cyclic(
650            |controller: &std::rc::Weak<
651                ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>,
652            >| {
653                let controller = controller.clone();
654                ScaffoldFeatureController::new(
655                    // We provide a fallback key so that if back-to-back material banners happen
656                    // to match in structure, material ink splashes and highlights don't survive
657                    // from one to the next.
658                    material_banner.with_animation(
659                        self.material_banner_controller(app).erase(),
660                        Some(KeyRef::Local(Rc::new(UniqueKey::new()))),
661                    ),
662                    Completer::new(),
663                    Rc::new(move |app: &mut App| {
664                        debug_assert!(
665                            app.get(self)
666                                .material_banners
667                                .front()
668                                .zip(controller.upgrade())
669                                .is_some_and(|(first, controller)| Rc::ptr_eq(first, &controller))
670                        );
671                        self.hide_current_material_banner(app, MaterialBannerClosedReason::Hide);
672                    }),
673                    // MaterialBanner doesn't use a builder function so setState() wouldn't
674                    // rebuild it
675                    None,
676                )
677            },
678        );
679        let added = Rc::clone(&controller);
680        self.set_state(app, move |state| {
681            state.material_banners.push_back(added);
682        });
683        self.update_scaffolds(app);
684        controller
685    }
686
687    fn handle_material_banner_status_changed(
688        self: Handle<Self>,
689        app: &mut App,
690        status: AnimationStatus,
691    ) {
692        match status {
693            AnimationStatus::Dismissed => {
694                debug_assert!(!app.get(self).material_banners.is_empty());
695                self.set_state(app, |state| {
696                    state.material_banners.pop_front();
697                });
698                self.update_scaffolds(app);
699                if !app.get(self).material_banners.is_empty() {
700                    self.material_banner_controller(app).forward(app, None);
701                }
702            }
703            AnimationStatus::Completed => {
704                self.update_scaffolds(app);
705            }
706            AnimationStatus::Forward | AnimationStatus::Reverse => {}
707        }
708    }
709
710    /// Removes the current [`MaterialBanner`] (if any) immediately from registered
711    /// [`Scaffold`]s.
712    ///
713    /// The removed material banner does not run its normal exit animation. If there are
714    /// any queued material banners, they begin their entrance animation immediately.
715    ///
716    /// Dart's default `reason` is [`MaterialBannerClosedReason::Remove`].
717    pub fn remove_current_material_banner(
718        self: Handle<Self>,
719        app: &mut App,
720        reason: MaterialBannerClosedReason,
721    ) {
722        let Some(first) = app.get(self).material_banners.front().cloned() else {
723            return;
724        };
725        let completer = first.completer.clone();
726        if !completer.is_completed() {
727            completer.complete(app, reason);
728        }
729
730        // This will trigger the animation's status callback.
731        self.material_banner_controller(app).set_value(app, 0.0);
732    }
733
734    /// Removes the current [`MaterialBanner`] by running its normal exit animation.
735    ///
736    /// The closed completer is called after the animation is complete.
737    ///
738    /// Dart's default `reason` is [`MaterialBannerClosedReason::Hide`].
739    pub fn hide_current_material_banner(
740        self: Handle<Self>,
741        app: &mut App,
742        reason: MaterialBannerClosedReason,
743    ) {
744        if app.get(self).material_banners.is_empty()
745            || self.material_banner_controller(app).is_dismissed(app)
746        {
747            return;
748        }
749        let completer = app
750            .get(self)
751            .material_banners
752            .front()
753            .expect("checked above")
754            .completer
755            .clone();
756        let controller = self.material_banner_controller(app).handle();
757        if app.get(self).accessible_navigation {
758            controller.set_value(app, 0.0);
759            completer.complete(app, reason);
760        } else {
761            controller.reverse(app, None).when_complete(
762                app,
763                Listener::new(move |app| {
764                    debug_assert!(self.mounted(app));
765                    if !completer.is_completed() {
766                        completer.complete(app, reason);
767                    }
768                }),
769            );
770        }
771    }
772
773    /// Removes all the [`MaterialBanner`]s currently in queue by clearing the queue
774    /// and running normal exit animation on the current [`MaterialBanner`].
775    pub fn clear_material_banners(self: Handle<Self>, app: &mut App) {
776        if app.get(self).material_banners.is_empty()
777            || self.material_banner_controller(app).is_dismissed(app)
778        {
779            return;
780        }
781        let material_banners = &mut app.get_mut(self).material_banners;
782        let current_material_banner = material_banners.pop_front().expect("checked above");
783        material_banners.clear();
784        material_banners.push_back(current_material_banner);
785        self.hide_current_material_banner(app, MaterialBannerClosedReason::Hide);
786    }
787}
788
789impl TickerProviderStateMixin for ScaffoldMessengerState {
790    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
791        &app.get(self).ticker_provider
792    }
793
794    fn ticker_provider_data_mut(
795        self: Handle<Self>,
796        app: &mut App,
797    ) -> &mut TickerProviderStateMixinData {
798        &mut app.get_mut(self).ticker_provider
799    }
800}
801
802/// Dart's `vsync: this`.
803impl TickerProviderObject for ScaffoldMessengerState {
804    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
805        TickerProviderStateMixin::create_ticker(self, app, on_tick)
806    }
807}
808
809impl State for ScaffoldMessengerState {
810    type Widget = ScaffoldMessenger;
811    waft_widgets::state_accessors!();
812
813    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
814        let context = self.context(app);
815        app.get_mut(self).accessible_navigation =
816            MediaQuery::accessible_navigation_of(app, context);
817    }
818
819    fn activate(self: Handle<Self>, app: &mut App) {
820        TickerProviderStateMixin::activate(self, app);
821    }
822
823    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
824        debug_assert!(waft_widgets::debug_check_has_media_query(app, context));
825        app.get_mut(self).accessible_navigation =
826            MediaQuery::accessible_navigation_of(app, context);
827
828        if let Some(first) = app.get(self).snack_bars.front().cloned() {
829            let route = AnyModalRoute::of(app, context);
830            if route.is_none_or(|route| route.as_route().is_current(app)) {
831                let controller = self.snack_bar_controller(app).handle();
832                if controller.is_completed(app) && app.get(self).snack_bar_timer.is_none() {
833                    let snack_bar = first.widget();
834                    let persist = snack_bar.effective_persist();
835                    let timer = Timer::new(
836                        app,
837                        snack_bar.duration,
838                        Listener::new(move |app| {
839                            debug_assert!(controller.is_forward_or_completed(app));
840                            // Look up MediaQuery again in case the setting changed.
841                            if persist {
842                                return;
843                            }
844                            self.hide_current_snack_bar(app, SnackBarClosedReason::Timeout);
845                        }),
846                    );
847                    app.get_mut(self).snack_bar_timer = Some(timer);
848                }
849            }
850        }
851
852        ScaffoldMessengerScope {
853            scaffold_messenger_state: self,
854            child: self.widget(app).child.clone(),
855        }
856        .into_widget()
857    }
858
859    fn dispose(self: Handle<Self>, app: &mut App) {
860        if let Some(controller) = app.get(self).material_banner_controller.handle() {
861            controller.dispose(app);
862        }
863        if let Some(controller) = app.get(self).snack_bar_controller.handle() {
864            controller.dispose(app);
865        }
866        if let Some(timer) = app.get_mut(self).snack_bar_timer.take() {
867            timer.cancel(app);
868        }
869        TickerProviderStateMixin::dispose(self, app);
870    }
871}
872
873/// Dart's `_ScaffoldMessengerScope`.
874#[derive(Debug)]
875struct ScaffoldMessengerScope {
876    scaffold_messenger_state: Handle<ScaffoldMessengerState>,
877    child: WidgetRef,
878}
879
880impl InheritedWidget for ScaffoldMessengerScope {
881    fn child(&self) -> &WidgetRef {
882        &self.child
883    }
884
885    fn update_should_notify(&self, old: &ScaffoldMessengerScope) -> bool {
886        self.scaffold_messenger_state != old.scaffold_messenger_state
887    }
888}
889
890/// The geometry of the [`Scaffold`] after all its contents have been laid out
891/// except the `FloatingActionButton`.
892///
893/// The [`Scaffold`] passes this pre-layout geometry to its
894/// [`FloatingActionButtonLocation`], which produces an `Offset` that the
895/// [`Scaffold`] uses to position the `FloatingActionButton`.
896///
897/// For a description of the [`Scaffold`]'s geometry after it has
898/// finished laying out, see the [`ScaffoldGeometry`].
899#[derive(Clone, Copy, Debug)]
900pub struct ScaffoldPrelayoutGeometry {
901    /// The [`Size`] of [`Scaffold::floating_action_button`].
902    ///
903    /// If [`Scaffold::floating_action_button`] is null, this will be [`Size::ZERO`].
904    pub floating_action_button_size: Size,
905
906    /// The [`Size`] of the [`Scaffold`]'s [`BottomSheet`].
907    ///
908    /// If the [`Scaffold`] is not currently showing a [`BottomSheet`],
909    /// this will be [`Size::ZERO`].
910    pub bottom_sheet_size: Size,
911
912    /// The vertical distance from the Scaffold's origin to the bottom of
913    /// [`Scaffold::body`].
914    ///
915    /// This is useful in a [`FloatingActionButtonLocation`] designed to
916    /// place the `FloatingActionButton` at the bottom of the screen, while
917    /// keeping it above the [`BottomSheet`], the [`Scaffold::bottom_navigation_bar`],
918    /// or the keyboard.
919    ///
920    /// The [`Scaffold::body`] is laid out with respect to [`min_insets`](Self::min_insets)
921    /// already. This means that a [`FloatingActionButtonLocation`] does not need to factor in
922    /// `EdgeInsets.bottom` of [`min_insets`](Self::min_insets) when aligning a
923    /// `FloatingActionButton` to [`content_bottom`](Self::content_bottom).
924    pub content_bottom: f64,
925
926    /// The vertical distance from the [`Scaffold`]'s origin to the top of
927    /// [`Scaffold::body`].
928    ///
929    /// This is useful in a [`FloatingActionButtonLocation`] designed to
930    /// place the `FloatingActionButton` at the top of the screen, while
931    /// keeping it below the `Scaffold.appBar`.
932    ///
933    /// The [`Scaffold::body`] is laid out with respect to [`min_insets`](Self::min_insets)
934    /// already. This means that a [`FloatingActionButtonLocation`] does not need to factor in
935    /// `EdgeInsets.top` of [`min_insets`](Self::min_insets) when aligning a
936    /// `FloatingActionButton` to [`content_top`](Self::content_top).
937    pub content_top: f64,
938
939    /// The minimum padding to inset the `FloatingActionButton` by for it
940    /// to remain visible.
941    ///
942    /// This value is the result of calling `MediaQueryData.padding` in the
943    /// [`Scaffold`]'s [`BuildContext`],
944    /// and is useful for insetting the `FloatingActionButton` to avoid features like
945    /// the system status bar or the keyboard.
946    ///
947    /// If [`Scaffold::resize_to_avoid_bottom_inset`] is set to false,
948    /// `EdgeInsets.bottom` of [`min_insets`](Self::min_insets) will be 0.0.
949    pub min_insets: EdgeInsets,
950
951    /// The minimum padding to inset interactive elements to be within a safe,
952    /// un-obscured space.
953    ///
954    /// This value reflects the `MediaQueryData.viewPadding` of the [`Scaffold`]'s
955    /// [`BuildContext`] when [`Scaffold::resize_to_avoid_bottom_inset`] is false or and
956    /// the `MediaQueryData.viewInsets` > 0.0. This helps distinguish between
957    /// different types of obstructions on the screen, such as software keyboards
958    /// and physical device notches.
959    pub min_view_padding: EdgeInsets,
960
961    /// The [`Size`] of the whole [`Scaffold`].
962    ///
963    /// If the [`Size`] of the [`Scaffold`]'s contents is modified by values such as
964    /// [`Scaffold::resize_to_avoid_bottom_inset`] or the keyboard opening, then the
965    /// [`scaffold_size`](Self::scaffold_size) will not reflect those changes.
966    ///
967    /// This means that [`FloatingActionButtonLocation`]s designed to reposition
968    /// the `FloatingActionButton` based on events such as the keyboard popping
969    /// up should use [`min_insets`](Self::min_insets) to make sure that the
970    /// `FloatingActionButton` is inset by enough to remain visible.
971    ///
972    /// See [`min_insets`](Self::min_insets) and `MediaQueryData.padding` for more information
973    /// on the appropriate insets to apply.
974    pub scaffold_size: Size,
975
976    /// The [`Size`] of the [`Scaffold`]'s [`SnackBar`].
977    ///
978    /// If the [`Scaffold`] is not showing a [`SnackBar`], this will be [`Size::ZERO`].
979    pub snack_bar_size: Size,
980
981    /// The [`Size`] of the [`Scaffold`]'s [`MaterialBanner`].
982    ///
983    /// If the [`Scaffold`] is not showing a [`MaterialBanner`], this will be [`Size::ZERO`].
984    pub material_banner_size: Size,
985
986    /// The [`TextDirection`] of the [`Scaffold`]'s [`BuildContext`].
987    pub text_direction: TextDirection,
988}
989
990impl ScaffoldPrelayoutGeometry {
991    /// Abstract const constructor. This constructor enables subclasses to provide
992    /// const constructors so that they can be used in const expressions.
993    #[expect(
994        clippy::too_many_arguments,
995        reason = "Dart's constructor takes every field as a required argument"
996    )]
997    pub const fn new(
998        bottom_sheet_size: Size,
999        content_bottom: f64,
1000        content_top: f64,
1001        floating_action_button_size: Size,
1002        min_insets: EdgeInsets,
1003        min_view_padding: EdgeInsets,
1004        scaffold_size: Size,
1005        snack_bar_size: Size,
1006        material_banner_size: Size,
1007        text_direction: TextDirection,
1008    ) -> ScaffoldPrelayoutGeometry {
1009        ScaffoldPrelayoutGeometry {
1010            floating_action_button_size,
1011            bottom_sheet_size,
1012            content_bottom,
1013            content_top,
1014            min_insets,
1015            min_view_padding,
1016            scaffold_size,
1017            snack_bar_size,
1018            material_banner_size,
1019            text_direction,
1020        }
1021    }
1022}
1023
1024/// A snapshot of a transition between two [`FloatingActionButtonLocation`]s.
1025///
1026/// [`ScaffoldState`] uses this to seamlessly change transition animations
1027/// when a running [`FloatingActionButtonLocation`] transition is interrupted by a new
1028/// transition.
1029struct TransitionSnapshotFabLocation {
1030    begin: FloatingActionButtonLocationRef,
1031    end: FloatingActionButtonLocationRef,
1032    animator: FloatingActionButtonAnimatorRef,
1033    progress: f64,
1034}
1035
1036impl FloatingActionButtonLocation for TransitionSnapshotFabLocation {
1037    fn get_offset(&self, scaffold_geometry: &ScaffoldPrelayoutGeometry) -> Offset {
1038        self.animator.get_offset(
1039            self.begin.get_offset(scaffold_geometry),
1040            self.end.get_offset(scaffold_geometry),
1041            self.progress,
1042        )
1043    }
1044}
1045
1046impl Debug for TransitionSnapshotFabLocation {
1047    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1048        write!(
1049            f,
1050            "_TransitionSnapshotFabLocation(begin: {:?}, end: {:?}, progress: {})",
1051            self.begin, self.end, self.progress
1052        )
1053    }
1054}
1055
1056/// Geometry information for [`Scaffold`] components after layout is finished.
1057///
1058/// To get a notifier for the scaffold geometry of a given
1059/// [`BuildContext`], use [`Scaffold::geometry_of`].
1060///
1061/// The ScaffoldGeometry is only available during the paint phase, because
1062/// its value is computed during the animation and layout phases prior to painting.
1063///
1064/// For an example of using the [`ScaffoldGeometry`], see the `BottomAppBar`,
1065/// which uses the [`ScaffoldGeometry`] to paint a notch around the
1066/// `FloatingActionButton`.
1067///
1068/// For information about the [`Scaffold`]'s geometry that is used while laying
1069/// out the `FloatingActionButton`, see [`ScaffoldPrelayoutGeometry`].
1070#[derive(Clone, Copy, Debug, Default)]
1071pub struct ScaffoldGeometry {
1072    /// The distance from the [`Scaffold`]'s top edge to the top edge of the
1073    /// rectangle in which the [`Scaffold::bottom_navigation_bar`] bar is laid out.
1074    ///
1075    /// Null if [`Scaffold::bottom_navigation_bar`] is null.
1076    pub bottom_navigation_bar_top: Option<f64>,
1077
1078    /// The [`Scaffold::floating_action_button`]'s bounding rectangle.
1079    ///
1080    /// This is null when there is no floating action button showing.
1081    pub floating_action_button_area: Option<Rect>,
1082}
1083
1084impl ScaffoldGeometry {
1085    /// Create an object that describes the geometry of a [`Scaffold`].
1086    pub const fn new() -> ScaffoldGeometry {
1087        ScaffoldGeometry {
1088            bottom_navigation_bar_top: None,
1089            floating_action_button_area: None,
1090        }
1091    }
1092
1093    /// Dart `ScaffoldGeometry(bottomNavigationBarTop:)`.
1094    pub fn bottom_navigation_bar_top(mut self, bottom_navigation_bar_top: f64) -> ScaffoldGeometry {
1095        self.bottom_navigation_bar_top = Some(bottom_navigation_bar_top);
1096        self
1097    }
1098
1099    /// Dart `ScaffoldGeometry(floatingActionButtonArea:)`.
1100    pub fn floating_action_button_area(
1101        mut self,
1102        floating_action_button_area: Rect,
1103    ) -> ScaffoldGeometry {
1104        self.floating_action_button_area = Some(floating_action_button_area);
1105        self
1106    }
1107
1108    fn scale_floating_action_button(self, scale_factor: f64) -> ScaffoldGeometry {
1109        if scale_factor == 1.0 {
1110            return self;
1111        }
1112
1113        if scale_factor == 0.0 {
1114            return ScaffoldGeometry {
1115                bottom_navigation_bar_top: self.bottom_navigation_bar_top,
1116                floating_action_button_area: None,
1117            };
1118        }
1119
1120        let area = self
1121            .floating_action_button_area
1122            .expect("a scaled floating action button has an area");
1123        let scaled_button = Rect::lerp(Some(area.center() & Size::ZERO), Some(area), scale_factor)
1124            .expect("both rects are given");
1125        self.copy_with().floating_action_button_area(scaled_button)
1126    }
1127
1128    /// Creates a copy of this [`ScaffoldGeometry`] but with the given fields replaced with
1129    /// the new values.
1130    pub fn copy_with(&self) -> ScaffoldGeometry {
1131        *self
1132    }
1133}
1134
1135/// Dart's `_ScaffoldGeometryNotifier`: the [`ScaffoldGeometry`] a scaffold publishes to
1136/// [`Scaffold::geometry_of`] as its layout and its floating action button's scale change.
1137pub struct ScaffoldGeometryNotifier {
1138    change_notifier: ChangeNotifierData,
1139    context: BuildContext,
1140    floating_action_button_scale: Option<f64>,
1141    geometry: ScaffoldGeometry,
1142}
1143
1144impl ScaffoldGeometryNotifier {
1145    fn new(app: &mut App, geometry: ScaffoldGeometry, context: BuildContext) -> Ref<Self> {
1146        app.create(ScaffoldGeometryNotifier {
1147            change_notifier: ChangeNotifierData::default(),
1148            context,
1149            floating_action_button_scale: None,
1150            geometry,
1151        })
1152    }
1153
1154    /// The scaffold's geometry, with the floating action button's area scaled by its current
1155    /// scale. Dart's `value` getter.
1156    ///
1157    /// # Panics
1158    ///
1159    /// In a debug build, outside the paint phase.
1160    pub fn value(self: Handle<Self>, app: &App) -> ScaffoldGeometry {
1161        if cfg!(debug_assertions) {
1162            let render_object = app.get(self).context.find_render_object(app);
1163            let doing_paint = render_object
1164                .and_then(|render_object| render_object.owner(app))
1165                .is_some_and(|owner| owner.debug_doing_paint(app));
1166            assert!(
1167                doing_paint,
1168                "Scaffold.geometryOf() must only be accessed during the paint phase.\n\
1169                 The ScaffoldGeometry is only available during the paint phase, because \
1170                 its value is computed during the animation and layout phases prior to painting."
1171            );
1172        }
1173
1174        let notifier = app.get(self);
1175        notifier.geometry.scale_floating_action_button(
1176            notifier
1177                .floating_action_button_scale
1178                .expect("the floating action button transition sets a scale"),
1179        )
1180    }
1181
1182    fn update_with(
1183        self: Handle<Self>,
1184        app: &mut App,
1185        bottom_navigation_bar_top: Option<f64>,
1186        floating_action_button_area: Option<Rect>,
1187        floating_action_button_scale: Option<f64>,
1188    ) {
1189        let notifier = app.get_mut(self);
1190        notifier.floating_action_button_scale =
1191            floating_action_button_scale.or(notifier.floating_action_button_scale);
1192        notifier.geometry = ScaffoldGeometry {
1193            bottom_navigation_bar_top: bottom_navigation_bar_top
1194                .or(notifier.geometry.bottom_navigation_bar_top),
1195            floating_action_button_area: floating_action_button_area
1196                .or(notifier.geometry.floating_action_button_area),
1197        };
1198        self.notify_listeners(app);
1199    }
1200
1201    fn dispose(self: Handle<Self>, app: &mut App) {
1202        ChangeNotifierData::dispose(app, self);
1203    }
1204}
1205
1206impl ChangeNotifier for ScaffoldGeometryNotifier {
1207    fn change_notifier_data(&self) -> &ChangeNotifierData {
1208        &self.change_notifier
1209    }
1210
1211    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1212        &mut self.change_notifier
1213    }
1214}
1215
1216impl Debug for ScaffoldGeometryNotifier {
1217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1218        f.debug_struct("_ScaffoldGeometryNotifier")
1219            .field(
1220                "floatingActionButtonScale",
1221                &self.floating_action_button_scale,
1222            )
1223            .field("geometry", &self.geometry)
1224            .finish_non_exhaustive()
1225    }
1226}
1227
1228// Used to communicate the height of the Scaffold's bottomNavigationBar and
1229// persistentFooterButtons to the LayoutBuilder which builds the Scaffold's body.
1230//
1231// Scaffold expects a _BodyBoxConstraints to be passed to the _BodyBuilder
1232// widget's LayoutBuilder, see _ScaffoldLayout.performLayout(). The BoxConstraints
1233// methods that construct new BoxConstraints objects, like copyWith() have not
1234// been overridden here because we expect the _BodyBoxConstraintsObject to be
1235// passed along unmodified to the LayoutBuilder. If that changes in the future
1236// then _BodyBuilder will assert.
1237#[derive(Debug)]
1238struct BodyBoxConstraints {
1239    bottom_widgets_height: f64,
1240    app_bar_height: f64,
1241    material_banner_height: f64,
1242}
1243
1244impl BodyBoxConstraints {
1245    /// Dart's `_BodyBoxConstraints(...)`: the instance, whose plain value is
1246    /// `super(maxWidth:, maxHeight:)`.
1247    #[expect(
1248        clippy::new_ret_no_self,
1249        reason = "a BoxConstraints subclass instance is an AnyBoxConstraints"
1250    )]
1251    fn new(
1252        max_width: f64,
1253        max_height: f64,
1254        bottom_widgets_height: f64,
1255        app_bar_height: f64,
1256        material_banner_height: f64,
1257    ) -> AnyBoxConstraints {
1258        debug_assert!(bottom_widgets_height >= 0.0);
1259        debug_assert!(app_bar_height >= 0.0);
1260        debug_assert!(material_banner_height >= 0.0);
1261        AnyBoxConstraints::with_shared(
1262            BoxConstraints::new()
1263                .max_width(max_width)
1264                .max_height(max_height),
1265            Rc::new(BodyBoxConstraints {
1266                bottom_widgets_height,
1267                app_bar_height,
1268                material_banner_height,
1269            }),
1270        )
1271    }
1272}
1273
1274impl BoxConstraintsExtension for BodyBoxConstraints {
1275    fn as_any(&self) -> &dyn Any {
1276        self
1277    }
1278
1279    // RenderObject.layout() will only short-circuit its call to its performLayout
1280    // method if the new layout constraints are not == to the current constraints.
1281    // If the height of the bottom widgets has changed, even though the constraints'
1282    // min and max values have not, we still want performLayout to happen.
1283    fn eq_extension(&self, other: &dyn BoxConstraintsExtension) -> bool {
1284        other
1285            .as_any()
1286            .downcast_ref::<BodyBoxConstraints>()
1287            .is_some_and(|other| {
1288                other.material_banner_height == self.material_banner_height
1289                    && other.bottom_widgets_height == self.bottom_widgets_height
1290                    && other.app_bar_height == self.app_bar_height
1291            })
1292    }
1293}
1294
1295// Used to communicate the keyboard inset computed by _ScaffoldLayout to the
1296// persistent bottom sheet, in the same way _BodyBoxConstraints communicates
1297// layout information to the body.
1298#[derive(Debug)]
1299struct BottomSheetBoxConstraints {
1300    // The distance between the bottom of the sheet's content, which avoids the
1301    // keyboard, and the bottom edge of the sheet's Material, which extends
1302    // behind it. Zero when the keyboard is closed or when
1303    // Scaffold.resizeToAvoidBottomInset is false.
1304    keyboard_inset: f64,
1305}
1306
1307impl BottomSheetBoxConstraints {
1308    /// Dart's `_BottomSheetBoxConstraints(...)`: the instance, whose plain value is
1309    /// `super(maxWidth:, maxHeight:)`.
1310    #[expect(
1311        clippy::new_ret_no_self,
1312        reason = "a BoxConstraints subclass instance is an AnyBoxConstraints"
1313    )]
1314    fn new(max_width: f64, max_height: f64, keyboard_inset: f64) -> AnyBoxConstraints {
1315        debug_assert!(keyboard_inset >= 0.0);
1316        AnyBoxConstraints::with_shared(
1317            BoxConstraints::new()
1318                .max_width(max_width)
1319                .max_height(max_height),
1320            Rc::new(BottomSheetBoxConstraints { keyboard_inset }),
1321        )
1322    }
1323}
1324
1325impl BoxConstraintsExtension for BottomSheetBoxConstraints {
1326    fn as_any(&self) -> &dyn Any {
1327        self
1328    }
1329
1330    fn eq_extension(&self, other: &dyn BoxConstraintsExtension) -> bool {
1331        other
1332            .as_any()
1333            .downcast_ref::<BottomSheetBoxConstraints>()
1334            .is_some_and(|other| other.keyboard_inset == self.keyboard_inset)
1335    }
1336}
1337
1338// Provides _BottomSheetBoxConstraints.keyboardInset to the _StandardBottomSheets
1339// in the Scaffold's bottom sheet slot, which are built before layout.
1340#[derive(Debug)]
1341struct BottomSheetKeyboardInset {
1342    inset: f64,
1343    child: WidgetRef,
1344}
1345
1346impl BottomSheetKeyboardInset {
1347    fn of(app: &mut App, context: BuildContext) -> f64 {
1348        context
1349            .depend_on_inherited_widget_of_exact_type::<BottomSheetKeyboardInset>(app)
1350            .map_or(0.0, |scope| scope.inset)
1351    }
1352}
1353
1354impl InheritedWidget for BottomSheetKeyboardInset {
1355    fn child(&self) -> &WidgetRef {
1356        &self.child
1357    }
1358
1359    fn update_should_notify(&self, old_widget: &BottomSheetKeyboardInset) -> bool {
1360        self.inset != old_widget.inset
1361    }
1362}
1363
1364// Used when Scaffold.extendBody is true to wrap the scaffold's body in a MediaQuery
1365// whose padding accounts for the height of the bottomNavigationBar and/or the
1366// persistentFooterButtons.
1367//
1368// The bottom widgets' height is passed along via the _BodyBoxConstraints parameter.
1369// The constraints parameter is constructed in_ScaffoldLayout.performLayout().
1370#[derive(Debug)]
1371struct BodyBuilder {
1372    body: WidgetRef,
1373    extend_body: bool,
1374    extend_body_behind_app_bar: bool,
1375}
1376
1377impl BodyBuilder {
1378    fn new(extend_body: bool, extend_body_behind_app_bar: bool, body: WidgetRef) -> BodyBuilder {
1379        BodyBuilder {
1380            body,
1381            extend_body,
1382            extend_body_behind_app_bar,
1383        }
1384    }
1385}
1386
1387impl StatelessWidget for BodyBuilder {
1388    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1389        if !self.extend_body && !self.extend_body_behind_app_bar {
1390            return self.body.clone();
1391        }
1392
1393        let extend_body = self.extend_body;
1394        let extend_body_behind_app_bar = self.extend_body_behind_app_bar;
1395        let body = self.body.clone();
1396        LayoutBuilder::new(move |app, context, constraints| {
1397            let body_constraints = constraints
1398                .extension::<BodyBoxConstraints>()
1399                .expect("the scaffold lays out its body with _BodyBoxConstraints");
1400            let metrics = MediaQuery::of(app, context);
1401
1402            let bottom = if extend_body {
1403                f64::max(
1404                    metrics.padding.bottom,
1405                    body_constraints.bottom_widgets_height,
1406                )
1407            } else {
1408                metrics.padding.bottom
1409            };
1410
1411            let top = if extend_body_behind_app_bar {
1412                f64::max(
1413                    metrics.padding.top,
1414                    body_constraints.app_bar_height + body_constraints.material_banner_height,
1415                )
1416            } else {
1417                metrics.padding.top
1418            };
1419
1420            let padding = metrics
1421                .padding
1422                .copy_with(None, Some(top), None, Some(bottom));
1423            MediaQuery::new(metrics.copy_with().padding(padding), body.clone()).into_widget()
1424        })
1425        .into_widget()
1426    }
1427}
1428
1429/// Dart's `_ScaffoldLayout`.
1430struct ScaffoldLayout {
1431    extend_body: bool,
1432    extend_body_behind_app_bar: bool,
1433    min_insets: EdgeInsets,
1434    min_view_padding: EdgeInsets,
1435    text_direction: TextDirection,
1436    geometry_notifier: Ref<ScaffoldGeometryNotifier>,
1437
1438    previous_floating_action_button_location: FloatingActionButtonLocationRef,
1439    current_floating_action_button_location: FloatingActionButtonLocationRef,
1440    floating_action_button_move_animation: AnimationRef<f64>,
1441    /// Dart's `super(relayout: floatingActionButtonMoveAnimation)`.
1442    relayout: Rc<dyn Listenable>,
1443    floating_action_button_motion_animator: FloatingActionButtonAnimatorRef,
1444
1445    is_snack_bar_floating: bool,
1446    snack_bar_width: Option<f64>,
1447
1448    extend_body_behind_material_banner: bool,
1449}
1450
1451impl ScaffoldLayout {
1452    /// Whether the snack bar sits above a floating action button at `location`; Dart's
1453    /// switch over the standard locations, which compares them by identity.
1454    fn shows_snack_bar_above_fab(location: &FloatingActionButtonLocationRef) -> bool {
1455        let top_locations = [
1456            <dyn FloatingActionButtonLocation>::start_top(),
1457            <dyn FloatingActionButtonLocation>::center_top(),
1458            <dyn FloatingActionButtonLocation>::end_top(),
1459            <dyn FloatingActionButtonLocation>::mini_start_top(),
1460            <dyn FloatingActionButtonLocation>::mini_center_top(),
1461            <dyn FloatingActionButtonLocation>::mini_end_top(),
1462        ];
1463        !top_locations
1464            .iter()
1465            .any(|top_location| Rc::ptr_eq(top_location, location))
1466    }
1467}
1468
1469impl MultiChildLayoutDelegate for ScaffoldLayout {
1470    fn relayout(&self) -> Option<&Rc<dyn Listenable>> {
1471        Some(&self.relayout)
1472    }
1473
1474    fn perform_layout(&self, app: &mut App, children: &mut MultiChildLayoutChildren, size: Size) {
1475        let loose_constraints = BoxConstraints::loose(size);
1476
1477        // This part of the layout has the same effect as putting the app bar and
1478        // body in a column and making the body flexible. What's different is that
1479        // in this case the app bar appears _after_ the body in the stacking order,
1480        // so the app bar's shadow is drawn on top of the body.
1481
1482        let full_width_constraints = loose_constraints.tighten(Some(size.width()), None);
1483        let bottom = size.height();
1484        let mut content_top = 0.0;
1485        let mut bottom_widgets_height = 0.0;
1486        let mut app_bar_height = 0.0;
1487
1488        if children.has_child(&ScaffoldSlot::AppBar.id()) {
1489            app_bar_height = children
1490                .layout_child(app, &ScaffoldSlot::AppBar.id(), full_width_constraints)
1491                .height();
1492            content_top = if self.extend_body_behind_app_bar {
1493                0.0
1494            } else {
1495                app_bar_height
1496            };
1497            children.position_child(app, &ScaffoldSlot::AppBar.id(), Offset::ZERO);
1498        }
1499
1500        let mut bottom_navigation_bar_top = None;
1501        if children.has_child(&ScaffoldSlot::BottomNavigationBar.id()) {
1502            let bottom_navigation_bar_height = children
1503                .layout_child(
1504                    app,
1505                    &ScaffoldSlot::BottomNavigationBar.id(),
1506                    full_width_constraints,
1507                )
1508                .height();
1509            bottom_widgets_height += bottom_navigation_bar_height;
1510            let top = f64::max(0.0, bottom - bottom_widgets_height);
1511            bottom_navigation_bar_top = Some(top);
1512            children.position_child(
1513                app,
1514                &ScaffoldSlot::BottomNavigationBar.id(),
1515                Offset::new(0.0, top),
1516            );
1517        }
1518
1519        if children.has_child(&ScaffoldSlot::PersistentFooter.id()) {
1520            let footer_constraints = BoxConstraints::new()
1521                .max_width(full_width_constraints.max_width)
1522                .max_height(f64::max(0.0, bottom - bottom_widgets_height - content_top));
1523            let persistent_footer_height = children
1524                .layout_child(
1525                    app,
1526                    &ScaffoldSlot::PersistentFooter.id(),
1527                    footer_constraints,
1528                )
1529                .height();
1530            bottom_widgets_height += persistent_footer_height;
1531            children.position_child(
1532                app,
1533                &ScaffoldSlot::PersistentFooter.id(),
1534                Offset::new(0.0, f64::max(0.0, bottom - bottom_widgets_height)),
1535            );
1536        }
1537
1538        let mut material_banner_size = Size::ZERO;
1539        if children.has_child(&ScaffoldSlot::MaterialBanner.id()) {
1540            material_banner_size = children.layout_child(
1541                app,
1542                &ScaffoldSlot::MaterialBanner.id(),
1543                full_width_constraints,
1544            );
1545            children.position_child(
1546                app,
1547                &ScaffoldSlot::MaterialBanner.id(),
1548                Offset::new(0.0, app_bar_height),
1549            );
1550
1551            // Push content down only if elevation is 0.
1552            if !self.extend_body_behind_material_banner {
1553                content_top += material_banner_size.height();
1554            }
1555        }
1556
1557        // Set the content bottom to account for the greater of the height of any
1558        // bottom-anchored material widgets or of the keyboard or other
1559        // bottom-anchored system UI.
1560        let content_bottom = f64::max(
1561            0.0,
1562            bottom - f64::max(self.min_insets.bottom, bottom_widgets_height),
1563        );
1564
1565        // When the keyboard lifts the bottom sheet's content above it, the sheet's
1566        // Material keeps extending down to the edge otherwise available to the
1567        // sheet (above any bottom bars), so that a translucent keyboard shows the
1568        // sheet's color rather than the Scaffold's background.
1569        let bottom_sheet_keyboard_inset =
1570            f64::max(0.0, bottom - bottom_widgets_height - content_bottom);
1571
1572        if children.has_child(&ScaffoldSlot::Body.id()) {
1573            let mut body_max_height = f64::max(0.0, content_bottom - content_top);
1574
1575            // When extendBody is true, the body is visible underneath the bottom widgets.
1576            // This does not apply when the area is obscured by the device keyboard.
1577            if self.extend_body && self.min_insets.bottom <= bottom_widgets_height {
1578                body_max_height += bottom_widgets_height;
1579                body_max_height = clamp_double(
1580                    body_max_height,
1581                    0.0,
1582                    loose_constraints.max_height - content_top,
1583                );
1584                debug_assert!(
1585                    body_max_height <= f64::max(0.0, loose_constraints.max_height - content_top)
1586                );
1587            } else {
1588                bottom_widgets_height = 0.0;
1589            }
1590
1591            let body_constraints = BodyBoxConstraints::new(
1592                full_width_constraints.max_width,
1593                body_max_height,
1594                bottom_widgets_height,
1595                app_bar_height,
1596                material_banner_size.height(),
1597            );
1598            children.layout_child(app, &ScaffoldSlot::Body.id(), body_constraints);
1599            children.position_child(app, &ScaffoldSlot::Body.id(), Offset::new(0.0, content_top));
1600        }
1601
1602        // The BottomSheet and the SnackBar are anchored to the bottom of the parent,
1603        // they're as wide as the parent and are given their intrinsic height. The
1604        // only difference is that SnackBar appears on the top side of the
1605        // BottomNavigationBar while the BottomSheet is stacked on top of it.
1606        //
1607        // If all three elements are present then either the center of the FAB straddles
1608        // the top edge of the BottomSheet or the bottom of the FAB is
1609        // kFloatingActionButtonMargin above the SnackBar, whichever puts the FAB
1610        // the farthest above the bottom of the parent. If only the FAB is has a
1611        // non-zero height then it's inset from the parent's right and bottom edges
1612        // by kFloatingActionButtonMargin.
1613
1614        let mut bottom_sheet_size = Size::ZERO;
1615        let mut snack_bar_size = Size::ZERO;
1616        if children.has_child(&ScaffoldSlot::BodyScrim.id()) {
1617            let bottom_sheet_scrim_constraints = BoxConstraints::new()
1618                .max_width(full_width_constraints.max_width)
1619                .max_height(content_bottom);
1620            children.layout_child(
1621                app,
1622                &ScaffoldSlot::BodyScrim.id(),
1623                bottom_sheet_scrim_constraints,
1624            );
1625            children.position_child(app, &ScaffoldSlot::BodyScrim.id(), Offset::ZERO);
1626        }
1627
1628        // Set the size of the SnackBar early if the behavior is fixed so
1629        // the FAB can be positioned correctly.
1630        if children.has_child(&ScaffoldSlot::SnackBar.id()) && !self.is_snack_bar_floating {
1631            snack_bar_size =
1632                children.layout_child(app, &ScaffoldSlot::SnackBar.id(), full_width_constraints);
1633        }
1634
1635        if children.has_child(&ScaffoldSlot::BottomSheet.id()) {
1636            let bottom_sheet_bottom = content_bottom + bottom_sheet_keyboard_inset;
1637            let bottom_sheet_constraints = BottomSheetBoxConstraints::new(
1638                full_width_constraints.max_width,
1639                f64::max(0.0, bottom_sheet_bottom - content_top),
1640                bottom_sheet_keyboard_inset,
1641            );
1642            let sheet_size = children.layout_child(
1643                app,
1644                &ScaffoldSlot::BottomSheet.id(),
1645                bottom_sheet_constraints,
1646            );
1647            children.position_child(
1648                app,
1649                &ScaffoldSlot::BottomSheet.id(),
1650                Offset::new(
1651                    (size.width() - sheet_size.width()) / 2.0,
1652                    bottom_sheet_bottom - sheet_size.height(),
1653                ),
1654            );
1655            // The floating action button is positioned relative to the sheet's
1656            // content, which ends at contentBottom, not to the Material behind the
1657            // keyboard.
1658            bottom_sheet_size = Size::new(
1659                sheet_size.width(),
1660                f64::max(0.0, sheet_size.height() - bottom_sheet_keyboard_inset),
1661            );
1662        }
1663
1664        let mut floating_action_button_rect = None;
1665        if children.has_child(&ScaffoldSlot::FloatingActionButton.id()) {
1666            let fab_size = children.layout_child(
1667                app,
1668                &ScaffoldSlot::FloatingActionButton.id(),
1669                loose_constraints,
1670            );
1671
1672            // To account for the FAB position being changed, we'll animate between
1673            // the old and new positions.
1674            let current_geometry = ScaffoldPrelayoutGeometry {
1675                bottom_sheet_size,
1676                content_bottom,
1677                // [appBarHeight] should be used instead of [contentTop] because
1678                // ScaffoldPrelayoutGeometry.contentTop must not be affected by
1679                // [extendBodyBehindAppBar].
1680                content_top: app_bar_height,
1681                floating_action_button_size: fab_size,
1682                min_insets: self.min_insets,
1683                scaffold_size: size,
1684                snack_bar_size,
1685                material_banner_size,
1686                text_direction: self.text_direction,
1687                min_view_padding: self.min_view_padding,
1688            };
1689            let current_fab_offset = self
1690                .current_floating_action_button_location
1691                .get_offset(&current_geometry);
1692            let previous_fab_offset = self
1693                .previous_floating_action_button_location
1694                .get_offset(&current_geometry);
1695            let fab_offset = self.floating_action_button_motion_animator.get_offset(
1696                previous_fab_offset,
1697                current_fab_offset,
1698                self.floating_action_button_move_animation.value(app),
1699            );
1700            children.position_child(app, &ScaffoldSlot::FloatingActionButton.id(), fab_offset);
1701            floating_action_button_rect = Some(fab_offset & fab_size);
1702        }
1703
1704        if children.has_child(&ScaffoldSlot::SnackBar.id()) {
1705            let has_custom_width = self
1706                .snack_bar_width
1707                .is_some_and(|snack_bar_width| snack_bar_width < size.width());
1708            if snack_bar_size == Size::ZERO {
1709                snack_bar_size = children.layout_child(
1710                    app,
1711                    &ScaffoldSlot::SnackBar.id(),
1712                    if has_custom_width {
1713                        loose_constraints
1714                    } else {
1715                        full_width_constraints
1716                    },
1717                );
1718            }
1719
1720            let show_above_fab = ScaffoldLayout::shows_snack_bar_above_fab(
1721                &self.current_floating_action_button_location,
1722            );
1723            let floating_action_button_rect = floating_action_button_rect
1724                .expect("a scaffold always has a floating action button slot");
1725            let snack_bar_y_offset_base = if floating_action_button_rect.size() != Size::ZERO
1726                && self.is_snack_bar_floating
1727                && show_above_fab
1728            {
1729                match bottom_navigation_bar_top {
1730                    Some(bottom_navigation_bar_top) => {
1731                        f64::min(bottom_navigation_bar_top, floating_action_button_rect.top)
1732                    }
1733                    None => floating_action_button_rect.top,
1734                }
1735            } else {
1736                // SnackBarBehavior.fixed applies a SafeArea automatically.
1737                // SnackBarBehavior.floating does not since the positioning is affected
1738                // if there is a FloatingActionButton (see condition above). If there is
1739                // no FAB, make sure we account for safe space when the SnackBar is
1740                // floating.
1741                let safe_y_offset_base = size.height() - self.min_view_padding.bottom;
1742                if self.is_snack_bar_floating {
1743                    f64::min(content_bottom, safe_y_offset_base)
1744                } else {
1745                    content_bottom
1746                }
1747            };
1748
1749            let x_offset = if has_custom_width {
1750                (size.width() - self.snack_bar_width.expect("has a custom width")) / 2.0
1751            } else {
1752                0.0
1753            };
1754            children.position_child(
1755                app,
1756                &ScaffoldSlot::SnackBar.id(),
1757                Offset::new(x_offset, snack_bar_y_offset_base - snack_bar_size.height()),
1758            );
1759
1760            // Whether a floating SnackBar has been offset too high.
1761            //
1762            // To improve the developer experience, this assert is done after the call to
1763            // positionChild. if we assert sooner the SnackBar is visible because its defaults
1764            // position is (0,0) and it can cause confusion to the user as the error message
1765            // states that the SnackBar is off screen.
1766            if cfg!(debug_assertions) && self.is_snack_bar_floating {
1767                let snack_bar_visible = (snack_bar_y_offset_base - snack_bar_size.height()) >= 0.0;
1768                assert!(
1769                    snack_bar_visible,
1770                    "Floating SnackBar presented off screen.\n\
1771                     A SnackBar with behavior property set to SnackBarBehavior.floating is fully \
1772                     or partially off screen because some or all the widgets provided to \
1773                     Scaffold.floatingActionButton, Scaffold.persistentFooterButtons and \
1774                     Scaffold.bottomNavigationBar take up too much vertical space.\n\
1775                     Consider constraining the size of these widgets to allow room for the \
1776                     SnackBar to be visible."
1777                );
1778            }
1779        }
1780
1781        if children.has_child(&ScaffoldSlot::StatusBar.id()) {
1782            children.layout_child(
1783                app,
1784                &ScaffoldSlot::StatusBar.id(),
1785                full_width_constraints.tighten(None, Some(self.min_insets.top)),
1786            );
1787            children.position_child(app, &ScaffoldSlot::StatusBar.id(), Offset::ZERO);
1788        }
1789
1790        if children.has_child(&ScaffoldSlot::Drawer.id()) {
1791            children.layout_child(app, &ScaffoldSlot::Drawer.id(), BoxConstraints::tight(size));
1792            children.position_child(app, &ScaffoldSlot::Drawer.id(), Offset::ZERO);
1793        }
1794
1795        if children.has_child(&ScaffoldSlot::EndDrawer.id()) {
1796            children.layout_child(
1797                app,
1798                &ScaffoldSlot::EndDrawer.id(),
1799                BoxConstraints::tight(size),
1800            );
1801            children.position_child(app, &ScaffoldSlot::EndDrawer.id(), Offset::ZERO);
1802        }
1803
1804        self.geometry_notifier.update_with(
1805            app,
1806            bottom_navigation_bar_top,
1807            floating_action_button_rect,
1808            None,
1809        );
1810    }
1811
1812    fn should_relayout(&self, old_delegate: &dyn MultiChildLayoutDelegate) -> bool {
1813        let old_delegate = old_delegate
1814            .as_any()
1815            .downcast_ref::<ScaffoldLayout>()
1816            .expect("the scaffold always lays out with a ScaffoldLayout");
1817        old_delegate.min_insets != self.min_insets
1818            || old_delegate.min_view_padding != self.min_view_padding
1819            || old_delegate.text_direction != self.text_direction
1820            || !Rc::ptr_eq(
1821                &old_delegate.previous_floating_action_button_location,
1822                &self.previous_floating_action_button_location,
1823            )
1824            || !Rc::ptr_eq(
1825                &old_delegate.current_floating_action_button_location,
1826                &self.current_floating_action_button_location,
1827            )
1828            || old_delegate.extend_body != self.extend_body
1829            || old_delegate.extend_body_behind_app_bar != self.extend_body_behind_app_bar
1830    }
1831
1832    fn as_any(&self) -> &dyn Any {
1833        self
1834    }
1835}
1836
1837impl Debug for ScaffoldLayout {
1838    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1839        f.debug_struct("_ScaffoldLayout")
1840            .field("minInsets", &self.min_insets)
1841            .field("minViewPadding", &self.min_view_padding)
1842            .field("textDirection", &self.text_direction)
1843            .field(
1844                "currentFloatingActionButtonLocation",
1845                &self.current_floating_action_button_location,
1846            )
1847            .finish_non_exhaustive()
1848    }
1849}
1850
1851/// Handler for scale and rotation animations in the `FloatingActionButton`.
1852///
1853/// Currently, there are two types of `FloatingActionButton` animations:
1854///
1855/// * Entrance/Exit animations, which this widget triggers
1856///   when the `FloatingActionButton` is added, updated, or removed.
1857/// * Motion animations, which are triggered by the [`Scaffold`]
1858///   when its [`FloatingActionButtonLocation`] is updated.
1859struct FloatingActionButtonTransition {
1860    child: Option<WidgetRef>,
1861    fab_move_animation: AnimationRef<f64>,
1862    fab_motion_animator: FloatingActionButtonAnimatorRef,
1863    geometry_notifier: Ref<ScaffoldGeometryNotifier>,
1864
1865    /// Controls the current child widget.child as it exits.
1866    current_controller: Ref<AnimationController>,
1867}
1868
1869impl Debug for FloatingActionButtonTransition {
1870    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1871        f.debug_struct("_FloatingActionButtonTransition")
1872            .field("child", &self.child)
1873            .field("fabMotionAnimator", &self.fab_motion_animator)
1874            .finish_non_exhaustive()
1875    }
1876}
1877
1878impl StatefulWidget for FloatingActionButtonTransition {
1879    type State = FloatingActionButtonTransitionState;
1880
1881    fn create_state(&self) -> FloatingActionButtonTransitionState {
1882        FloatingActionButtonTransitionState {
1883            state: StateData::new(),
1884            ticker_provider: TickerProviderStateMixinData::new(),
1885            previous_controller: None,
1886            previous_exit_scale_animation: None,
1887            previous_exit_rotation_curved_animation: None,
1888            current_entrance_scale_animation: None,
1889            previous_scale_animation: None,
1890            previous_rotation_animation: None,
1891            current_scale_animation: None,
1892            extended_current_scale_animation: None,
1893            current_rotation_animation: None,
1894            previous_child: None,
1895        }
1896    }
1897}
1898
1899/// Dart's `static final _FloatingActionButtonTransitionState._entranceTurnTween`, kept per
1900/// [`App`] and made on first use; shared by every transition, so the `App` keeps it for its life.
1901#[derive(Default)]
1902struct EntranceTurnTween {
1903    tweens: Option<(Ref<Tween<f64>>, Ref<CurveTween>)>,
1904}
1905
1906/// Dart's `_FloatingActionButtonTransitionState`.
1907struct FloatingActionButtonTransitionState {
1908    state: StateData<FloatingActionButtonTransition>,
1909    ticker_provider: TickerProviderStateMixinData,
1910    // The animations applied to the Floating Action Button when it is entering or exiting.
1911    // Controls the previous widget.child as it exits.
1912    previous_controller: Option<Ref<AnimationController>>,
1913    previous_exit_scale_animation: Option<Ref<CurvedAnimation>>,
1914    previous_exit_rotation_curved_animation: Option<Ref<CurvedAnimation>>,
1915    current_entrance_scale_animation: Option<Ref<CurvedAnimation>>,
1916    previous_scale_animation: Option<AnimationRef<f64>>,
1917    previous_rotation_animation: Option<Ref<TrainHoppingAnimation>>,
1918    // The animations to run, considering the widget's fabMoveAnimation and the
1919    // current/previous entrance/exit animations.
1920    current_scale_animation: Option<AnimationRef<f64>>,
1921    extended_current_scale_animation: Option<AnimationRef<f64>>,
1922    current_rotation_animation: Option<Ref<TrainHoppingAnimation>>,
1923    previous_child: Option<WidgetRef>,
1924}
1925
1926impl FloatingActionButtonTransitionState {
1927    fn previous_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
1928        app.get(self)
1929            .previous_controller
1930            .handle()
1931            .expect("set in init_state")
1932    }
1933
1934    /// Dart's `static final _entranceTurnTween`.
1935    fn entrance_turn_tween(app: &mut App) -> impl Animatable<f64> + Clone + 'static {
1936        let statics = app.singleton::<EntranceTurnTween>();
1937        let (tween, curve_tween) = match app.get(statics).tweens.clone() {
1938            Some(tweens) => tweens,
1939            None => {
1940                let tween = Tween::new(
1941                    app,
1942                    Some(1.0 - K_FLOATING_ACTION_BUTTON_TURN_INTERVAL),
1943                    Some(1.0),
1944                );
1945                let curve_tween = CurveTween::new(app, Curves::ease_in());
1946                app.get_mut(statics).tweens = Some((tween.clone(), curve_tween.clone()));
1947                (tween, curve_tween)
1948            }
1949        };
1950        tween.chain(curve_tween)
1951    }
1952
1953    fn dispose_animations(self: Handle<Self>, app: &mut App) {
1954        if let Some(animation) = app.get(self).previous_rotation_animation.handle() {
1955            animation.dispose(app);
1956        }
1957        if let Some(animation) = app.get(self).current_rotation_animation.handle() {
1958            animation.dispose(app);
1959        }
1960        self.remove_scale_listeners(app);
1961    }
1962
1963    /// Stops the two scale animations of the last `update_animations` from calling
1964    /// `on_progress_changed`.
1965    fn remove_scale_listeners(self: Handle<Self>, app: &mut App) {
1966        let this = app.get(self);
1967        for animation in [
1968            this.previous_scale_animation.clone(),
1969            this.current_scale_animation.clone(),
1970        ]
1971        .into_iter()
1972        .flatten()
1973        {
1974            animation.remove_listener(
1975                app,
1976                &Listener::handle_method(
1977                    self,
1978                    FloatingActionButtonTransitionState::on_progress_changed,
1979                ),
1980            );
1981        }
1982    }
1983
1984    /// Dart's `curvedAnimation?.dispose()`.
1985    fn dispose_curved_animation(app: &mut App, animation: Option<Handle<CurvedAnimation>>) {
1986        if let Some(animation) = animation {
1987            animation.dispose(app);
1988        }
1989    }
1990
1991    fn update_animations(self: Handle<Self>, app: &mut App) {
1992        let previous_controller = app
1993            .get(self)
1994            .previous_controller
1995            .clone()
1996            .expect("set in init_state");
1997        FloatingActionButtonTransitionState::dispose_curved_animation(
1998            app,
1999            app.get(self).previous_exit_scale_animation.handle(),
2000        );
2001        // Get the animations for exit and entrance.
2002        let previous_exit_scale_animation =
2003            CurvedAnimation::new(app, previous_controller.erase(), Curves::ease_in(), None);
2004        app.get_mut(self).previous_exit_scale_animation =
2005            Some(previous_exit_scale_animation.clone());
2006        FloatingActionButtonTransitionState::dispose_curved_animation(
2007            app,
2008            app.get(self)
2009                .previous_exit_rotation_curved_animation
2010                .handle(),
2011        );
2012        let previous_exit_rotation_curved_animation =
2013            CurvedAnimation::new(app, previous_controller.erase(), Curves::ease_in(), None);
2014        app.get_mut(self).previous_exit_rotation_curved_animation =
2015            Some(previous_exit_rotation_curved_animation.clone());
2016
2017        let previous_exit_rotation_tween = Tween::new(app, Some(1.0), Some(1.0));
2018        let previous_exit_rotation_animation = previous_exit_rotation_tween
2019            .animate(app, previous_exit_rotation_curved_animation.erase());
2020
2021        FloatingActionButtonTransitionState::dispose_curved_animation(
2022            app,
2023            app.get(self).current_entrance_scale_animation.handle(),
2024        );
2025        let current_controller = self.widget(app).current_controller.clone();
2026        let current_entrance_scale_animation =
2027            CurvedAnimation::new(app, current_controller.erase(), Curves::ease_in(), None);
2028        app.get_mut(self).current_entrance_scale_animation =
2029            Some(current_entrance_scale_animation.clone());
2030        let entrance_turn_tween = FloatingActionButtonTransitionState::entrance_turn_tween(app);
2031        let current_entrance_rotation_animation =
2032            current_controller.drive(app, entrance_turn_tween);
2033
2034        // Get the animations for when the FAB is moving.
2035        let fab_motion_animator = Rc::clone(&self.widget(app).fab_motion_animator);
2036        let fab_move_animation = self.widget(app).fab_move_animation.clone();
2037        let move_scale_animation =
2038            fab_motion_animator.get_scale_animation(app, fab_move_animation.clone());
2039        let move_rotation_animation =
2040            fab_motion_animator.get_rotation_animation(app, fab_move_animation);
2041
2042        // Aggregate the animations.
2043        let (
2044            previous_scale_animation,
2045            current_scale_animation,
2046            previous_rotation,
2047            current_rotation,
2048        ) = if Rc::ptr_eq(
2049            &fab_motion_animator,
2050            &<dyn FloatingActionButtonAnimator>::no_animation(),
2051        ) {
2052            (
2053                move_scale_animation.clone(),
2054                move_scale_animation,
2055                TrainHoppingAnimation::new(app, move_rotation_animation.clone(), None, None),
2056                TrainHoppingAnimation::new(app, move_rotation_animation, None, None),
2057            )
2058        } else {
2059            let previous_scale = AnimationMin::new(
2060                app,
2061                move_scale_animation.clone(),
2062                previous_exit_scale_animation.erase(),
2063            )
2064            .into_erased();
2065            let current_scale = AnimationMin::new(
2066                app,
2067                move_scale_animation.clone(),
2068                current_entrance_scale_animation.erase(),
2069            )
2070            .into_erased();
2071            (
2072                previous_scale,
2073                current_scale,
2074                TrainHoppingAnimation::new(
2075                    app,
2076                    previous_exit_rotation_animation,
2077                    Some(move_rotation_animation.clone()),
2078                    None,
2079                ),
2080                TrainHoppingAnimation::new(
2081                    app,
2082                    current_entrance_rotation_animation,
2083                    Some(move_rotation_animation),
2084                    None,
2085                ),
2086            )
2087        };
2088        let this = app.get_mut(self);
2089        this.previous_scale_animation = Some(previous_scale_animation.clone());
2090        this.current_scale_animation = Some(current_scale_animation.clone());
2091        this.previous_rotation_animation = Some(previous_rotation);
2092        this.current_rotation_animation = Some(current_rotation);
2093
2094        let interval_tween =
2095            CurveTween::new(app, Rc::new(Interval::new(0.0, 0.1, Curves::linear())));
2096        let extended_current_scale_animation = current_scale_animation.drive(app, interval_tween);
2097        let this = app.get_mut(self);
2098        this.extended_current_scale_animation = Some(extended_current_scale_animation);
2099        current_scale_animation.add_listener(
2100            app,
2101            Listener::handle_method(
2102                self,
2103                FloatingActionButtonTransitionState::on_progress_changed,
2104            ),
2105        );
2106        previous_scale_animation.add_listener(
2107            app,
2108            Listener::handle_method(
2109                self,
2110                FloatingActionButtonTransitionState::on_progress_changed,
2111            ),
2112        );
2113    }
2114
2115    fn handle_previous_animation_status_changed(
2116        self: Handle<Self>,
2117        app: &mut App,
2118        status: AnimationStatus,
2119    ) {
2120        if self.widget(app).child.is_some() && status.is_dismissed() {
2121            let current_controller = self.widget(app).current_controller.clone();
2122            debug_assert!(current_controller.is_dismissed(app));
2123            current_controller.forward(app, None);
2124        }
2125        self.set_state(app, |_| {});
2126    }
2127
2128    fn is_extended_floating_action_button(widget: Option<&WidgetRef>) -> bool {
2129        widget
2130            .and_then(|widget| downcast_widget::<FloatingActionButton>(&**widget))
2131            .is_some_and(|button| button.is_extended)
2132    }
2133
2134    fn on_progress_changed(self: Handle<Self>, app: &mut App) {
2135        let this = app.get(self);
2136        let previous = this
2137            .previous_scale_animation
2138            .clone()
2139            .expect("set by update_animations");
2140        let current = this
2141            .current_scale_animation
2142            .clone()
2143            .expect("set by update_animations");
2144        let scale = f64::max(previous.value(app), current.value(app));
2145        self.update_geometry_scale(app, scale);
2146    }
2147
2148    fn update_geometry_scale(self: Handle<Self>, app: &mut App, scale: f64) {
2149        let geometry_notifier = self.widget(app).geometry_notifier.clone();
2150        geometry_notifier.update_with(app, None, None, Some(scale));
2151    }
2152}
2153
2154impl TickerProviderStateMixin for FloatingActionButtonTransitionState {
2155    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
2156        &app.get(self).ticker_provider
2157    }
2158
2159    fn ticker_provider_data_mut(
2160        self: Handle<Self>,
2161        app: &mut App,
2162    ) -> &mut TickerProviderStateMixinData {
2163        &mut app.get_mut(self).ticker_provider
2164    }
2165}
2166
2167/// Dart's `vsync: this`.
2168impl TickerProviderObject for FloatingActionButtonTransitionState {
2169    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
2170        TickerProviderStateMixin::create_ticker(self, app, on_tick)
2171    }
2172}
2173
2174impl State for FloatingActionButtonTransitionState {
2175    type Widget = FloatingActionButtonTransition;
2176    waft_widgets::state_accessors!();
2177
2178    fn init_state(self: Handle<Self>, app: &mut App) {
2179        let previous_controller = AnimationController::new(
2180            app,
2181            None,
2182            Some(K_FLOATING_ACTION_BUTTON_SEGUE),
2183            None,
2184            0.0,
2185            1.0,
2186            waft_animation::AnimationBehavior::Normal,
2187            self,
2188        );
2189        previous_controller.add_status_listener(
2190            app,
2191            AnimationStatusListener::handle_method(
2192                self,
2193                FloatingActionButtonTransitionState::handle_previous_animation_status_changed,
2194            ),
2195        );
2196        app.get_mut(self).previous_controller = Some(previous_controller);
2197        self.update_animations(app);
2198
2199        if self.widget(app).child.is_some() {
2200            // If we start out with a child, have the child appear fully visible instead
2201            // of animating in.
2202            self.widget(app).current_controller.set_value(app, 1.0);
2203            // With FloatingActionButtonAnimator.noAnimation, floatingActionButtonScale is null.
2204            // Default to a scale of 1.0 to ensure the button remains visible.
2205            self.update_geometry_scale(app, 1.0);
2206        } else {
2207            // If we start without a child we update the geometry object with a
2208            // floating action button scale of 0, as it is not showing on the screen.
2209            self.update_geometry_scale(app, 0.0);
2210        }
2211    }
2212
2213    fn dispose(self: Handle<Self>, app: &mut App) {
2214        self.previous_controller(app).dispose(app);
2215        FloatingActionButtonTransitionState::dispose_curved_animation(
2216            app,
2217            app.get(self).previous_exit_scale_animation.handle(),
2218        );
2219        FloatingActionButtonTransitionState::dispose_curved_animation(
2220            app,
2221            app.get(self)
2222                .previous_exit_rotation_curved_animation
2223                .handle(),
2224        );
2225        FloatingActionButtonTransitionState::dispose_curved_animation(
2226            app,
2227            app.get(self).current_entrance_scale_animation.handle(),
2228        );
2229        self.dispose_animations(app);
2230        TickerProviderStateMixin::dispose(self, app);
2231    }
2232
2233    fn activate(self: Handle<Self>, app: &mut App) {
2234        TickerProviderStateMixin::activate(self, app);
2235    }
2236
2237    fn did_update_widget(
2238        self: Handle<Self>,
2239        app: &mut App,
2240        old_widget: &FloatingActionButtonTransition,
2241    ) {
2242        let widget = self.widget(app);
2243        if !Rc::ptr_eq(&old_widget.fab_motion_animator, &widget.fab_motion_animator)
2244            || old_widget.fab_move_animation != widget.fab_move_animation
2245        {
2246            self.dispose_animations(app);
2247            // Get the right scale and rotation animations to use for this widget.
2248            self.update_animations(app);
2249        }
2250        let widget = self.widget(app);
2251        let old_child_is_null = old_widget.child.is_none();
2252        let new_child_is_null = widget.child.is_none();
2253        if old_child_is_null == new_child_is_null
2254            && old_widget.child.as_ref().and_then(|child| child.key())
2255                == widget.child.as_ref().and_then(|child| child.key())
2256        {
2257            return;
2258        }
2259        let previous_controller = self.previous_controller(app);
2260        if previous_controller.is_dismissed(app) {
2261            let current_controller = widget.current_controller.clone();
2262            let current_value = current_controller.value(app);
2263            if current_value == 0.0 || old_widget.child.is_none() {
2264                // The current child hasn't started its entrance animation yet. We can
2265                // just skip directly to the new child's entrance.
2266                app.get_mut(self).previous_child = None;
2267                if self.widget(app).child.is_some() {
2268                    current_controller.forward(app, None);
2269                }
2270            } else {
2271                // Otherwise, we need to copy the state from the current controller to
2272                // the previous controller and run an exit animation for the previous
2273                // widget before running the entrance animation for the new child.
2274                app.get_mut(self).previous_child = old_widget.child.clone();
2275                previous_controller.set_value(app, current_value);
2276                previous_controller.reverse(app, None);
2277                current_controller.set_value(app, 0.0);
2278            }
2279        }
2280    }
2281
2282    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
2283        let this = app.get(self);
2284        let previous_scale_animation = this
2285            .previous_scale_animation
2286            .clone()
2287            .expect("update_animations");
2288        let previous_rotation_animation = this
2289            .previous_rotation_animation
2290            .clone()
2291            .expect("update_animations");
2292        let current_scale_animation = this
2293            .current_scale_animation
2294            .clone()
2295            .expect("update_animations");
2296        let extended_current_scale_animation = this
2297            .extended_current_scale_animation
2298            .clone()
2299            .expect("update_animations");
2300        let current_rotation_animation = this
2301            .current_rotation_animation
2302            .clone()
2303            .expect("update_animations");
2304        let previous_child = this.previous_child.clone();
2305        let child = self.widget(app).child.clone();
2306
2307        let mut children = Vec::new();
2308        if !self.previous_controller(app).is_dismissed(app) {
2309            if FloatingActionButtonTransitionState::is_extended_floating_action_button(
2310                previous_child.as_ref(),
2311            ) {
2312                let mut fade = FadeTransition::new(previous_scale_animation);
2313                if let Some(previous_child) = previous_child {
2314                    fade = fade.child(previous_child);
2315                }
2316                children.push(fade.into_widget());
2317            } else {
2318                let mut rotation = RotationTransition::new(previous_rotation_animation.erase());
2319                if let Some(previous_child) = previous_child {
2320                    rotation = rotation.child(previous_child);
2321                }
2322                children.push(
2323                    ScaleTransition::new(previous_scale_animation)
2324                        .child(rotation)
2325                        .into_widget(),
2326                );
2327            }
2328        }
2329        if FloatingActionButtonTransitionState::is_extended_floating_action_button(child.as_ref()) {
2330            let mut fade = FadeTransition::new(current_scale_animation);
2331            if let Some(child) = child {
2332                fade = fade.child(child);
2333            }
2334            children.push(
2335                ScaleTransition::new(extended_current_scale_animation)
2336                    .child(fade)
2337                    .into_widget(),
2338            );
2339        } else {
2340            let mut rotation = RotationTransition::new(current_rotation_animation.erase());
2341            if let Some(child) = child {
2342                rotation = rotation.child(child);
2343            }
2344            children.push(
2345                ScaleTransition::new(current_scale_animation)
2346                    .child(rotation)
2347                    .into_widget(),
2348            );
2349        }
2350        Stack::new()
2351            .alignment(AlignmentGeometry::CENTER_RIGHT)
2352            .children(children)
2353            .into_widget()
2354    }
2355}
2356
2357/// Dart's `Scaffold.bottomSheetScrimBuilder`: builds the scrim behind a bottom sheet from
2358/// the scaffold's scrim animation, or nothing.
2359pub type BottomSheetScrimBuilder =
2360    Rc<dyn Fn(&mut App, BuildContext, AnimationRef<f64>) -> Option<WidgetRef>>;
2361
2362/// Implements the basic Material Design visual layout structure.
2363///
2364/// This class provides APIs for showing drawers and bottom sheets.
2365///
2366/// To display a persistent bottom sheet, obtain the
2367/// [`ScaffoldState`] for the current [`BuildContext`] via [`Scaffold::of`] and use the
2368/// [`ScaffoldState::show_bottom_sheet`] function.
2369///
2370/// ## Scaffold layout, the keyboard, and display "notches"
2371///
2372/// The scaffold will expand to fill the available space. That usually
2373/// means that it will occupy its entire window or device screen. When
2374/// the device's keyboard appears the Scaffold's ancestor [`MediaQuery`]
2375/// widget's `MediaQueryData.viewInsets` changes and the Scaffold will
2376/// be rebuilt. By default the scaffold's [`body`](Self::body) is resized to make
2377/// room for the keyboard. To prevent the resize set
2378/// [`resize_to_avoid_bottom_inset`](Self::resize_to_avoid_bottom_inset) to false. In either
2379/// case the focused widget will be scrolled into view if it's within a scrollable
2380/// container.
2381///
2382/// The `MediaQueryData.padding` value defines areas that might
2383/// not be completely visible, like the display "notch" on the iPhone
2384/// X. The scaffold's [`body`](Self::body) is not inset by this padding value
2385/// although an `appBar` or [`bottom_navigation_bar`](Self::bottom_navigation_bar) will
2386/// typically cause the body to avoid the padding. The [`SafeArea`]
2387/// widget can be used within the scaffold's body to avoid areas
2388/// like display notches.
2389///
2390/// ## Floating action button with a draggable scrollable bottom sheet
2391///
2392/// If [`Scaffold::bottom_sheet`] is a `DraggableScrollableSheet`,
2393/// [`Scaffold::floating_action_button`] is set, and the bottom sheet is dragged to
2394/// cover greater than 70% of the Scaffold's height, two things happen in parallel:
2395///
2396///   * Scaffold starts to show scrim (see [`ScaffoldState::show_body_scrim`]), and
2397///   * [`Scaffold::floating_action_button`] is scaled down through an animation with a
2398///     `Curves.easeIn`, and disappears when the bottom sheet covers the entire Scaffold.
2399///
2400/// And as soon as the bottom sheet is dragged down to cover less than 70% of the
2401/// [`Scaffold`], the scrim disappears and [`Scaffold::floating_action_button`] animates back
2402/// to its normal size.
2403///
2404/// ## Troubleshooting
2405///
2406/// ### Nested Scaffolds
2407///
2408/// The Scaffold is designed to be a top level container for
2409/// a `MaterialApp`. This means that adding a Scaffold
2410/// to each route on a Material app will provide the app with
2411/// Material's basic visual layout structure.
2412///
2413/// It is typically not necessary to nest Scaffolds. For example, in a
2414/// tabbed UI, where the [`bottom_navigation_bar`](Self::bottom_navigation_bar) is a `TabBar`
2415/// and the body is a `TabBarView`, you might be tempted to make each tab bar
2416/// view a scaffold with a differently titled AppBar. Rather, it would be
2417/// better to add a listener to the `TabController` that updates the
2418/// AppBar.
2419///
2420/// Although there are some use cases, like a presentation app that
2421/// shows embedded flutter content, where nested scaffolds are
2422/// appropriate, it's best to avoid nesting scaffolds.
2423///
2424/// See also:
2425///
2426///  * `AppBar`, which is a horizontal bar typically shown at the top of an app
2427///    using the `appBar` property.
2428///  * `BottomAppBar`, which is a horizontal bar typically shown at the bottom
2429///    of an app using the [`bottom_navigation_bar`](Self::bottom_navigation_bar) property.
2430///  * [`FloatingActionButton`], which is a circular button typically shown in the
2431///    bottom right corner of the app using the
2432///    [`floating_action_button`](Self::floating_action_button) property.
2433///  * `Drawer`, which is a vertical panel that is typically displayed to the
2434///    left of the body (and often hidden on phones) using the [`drawer`](Self::drawer)
2435///    property.
2436///  * `BottomNavigationBar`, which is a horizontal array of buttons typically
2437///    shown along the bottom of the app using the
2438///    [`bottom_navigation_bar`](Self::bottom_navigation_bar) property.
2439///  * [`BottomSheet`], which is an overlay typically shown near the bottom of the
2440///    app. A bottom sheet can either be persistent, in which case it is shown
2441///    using the [`ScaffoldState::show_bottom_sheet`] method, or modal, in which case
2442///    it is shown using the `ShowModalBottomSheet` function.
2443pub struct Scaffold {
2444    pub key: Option<KeyRef>,
2445
2446    /// If true, and [`bottom_navigation_bar`](Self::bottom_navigation_bar) or
2447    /// [`persistent_footer_buttons`](Self::persistent_footer_buttons) is specified, then the
2448    /// [`body`](Self::body) extends to the bottom of the Scaffold, instead of only extending to
2449    /// the top of the [`bottom_navigation_bar`](Self::bottom_navigation_bar) or the
2450    /// [`persistent_footer_buttons`](Self::persistent_footer_buttons).
2451    ///
2452    /// If true, a [`MediaQuery`] widget whose bottom padding matches the height of the
2453    /// [`bottom_navigation_bar`](Self::bottom_navigation_bar) will be added above the
2454    /// scaffold's [`body`](Self::body).
2455    ///
2456    /// This property is often useful when the
2457    /// [`bottom_navigation_bar`](Self::bottom_navigation_bar) has a non-rectangular shape, like
2458    /// `CircularNotchedRectangle`, which adds a [`FloatingActionButton`] sized notch to the top
2459    /// edge of the bar. In this case specifying `extend_body: true` ensures that scaffold's
2460    /// body will be visible through the bottom navigation bar's notch.
2461    ///
2462    /// See also:
2463    ///
2464    ///  * [`extend_body_behind_app_bar`](Self::extend_body_behind_app_bar), which extends the
2465    ///    height of the body to the top of the scaffold.
2466    pub extend_body: bool,
2467
2468    /// Whether the drawer's barrier can be dismissed by tapping on it. Defaults to true.
2469    pub drawer_barrier_dismissible: bool,
2470
2471    /// If true, and an [`app_bar`](Self::app_bar) is specified, then the height of the
2472    /// [`body`](Self::body) is extended to include the height of the app bar and the top of
2473    /// the body is aligned with the top of the app bar.
2474    ///
2475    /// This is useful if the app bar's `AppBar.background_color` is not completely opaque.
2476    ///
2477    /// This property is false by default.
2478    ///
2479    /// See also:
2480    ///
2481    ///  * [`extend_body`](Self::extend_body), which extends the height of the body to the
2482    ///    bottom of the scaffold.
2483    pub extend_body_behind_app_bar: bool,
2484
2485    /// An app bar to display at the top of the scaffold.
2486    pub app_bar: Option<PreferredSizeWidgetRef>,
2487
2488    /// The primary content of the scaffold.
2489    ///
2490    /// Displayed below the `appBar`, above the bottom of the ambient
2491    /// [`MediaQuery`]'s `MediaQueryData.viewInsets`, and behind the
2492    /// [`floating_action_button`](Self::floating_action_button) and
2493    /// [`drawer`](Self::drawer). If [`resize_to_avoid_bottom_inset`](Self::resize_to_avoid_bottom_inset)
2494    /// is false then the body is not resized when the onscreen keyboard appears,
2495    /// i.e. it is not inset by `viewInsets.bottom`.
2496    ///
2497    /// The widget in the body of the scaffold is positioned at the top-left of
2498    /// the available space between the app bar and the bottom of the scaffold. To
2499    /// center this widget instead, consider putting it in a `Center` widget and
2500    /// having that be the body. To expand this widget instead, consider
2501    /// putting it in a [`SizedBox::expand`].
2502    ///
2503    /// If you have a column of widgets that should normally fit on the screen,
2504    /// but may overflow and would in such cases need to scroll, consider using a
2505    /// `ListView` as the body of the scaffold. This is also a good choice for
2506    /// the case where your body is a scrollable list.
2507    pub body: Option<WidgetRef>,
2508
2509    /// A button displayed floating above [`body`](Self::body), in the bottom right corner.
2510    ///
2511    /// Typically a [`FloatingActionButton`].
2512    pub floating_action_button: Option<WidgetRef>,
2513
2514    /// Responsible for determining where the
2515    /// [`floating_action_button`](Self::floating_action_button) should go.
2516    ///
2517    /// If null, the [`ScaffoldState`] will use the default location,
2518    /// `<dyn FloatingActionButtonLocation>::end_float()`.
2519    pub floating_action_button_location: Option<FloatingActionButtonLocationRef>,
2520
2521    /// Animator to move the [`floating_action_button`](Self::floating_action_button) to a new
2522    /// [`floating_action_button_location`](Self::floating_action_button_location).
2523    ///
2524    /// If null, the [`ScaffoldState`] will use the default animator,
2525    /// `<dyn FloatingActionButtonAnimator>::scaling()`.
2526    pub floating_action_button_animator: Option<FloatingActionButtonAnimatorRef>,
2527
2528    /// A set of buttons that are displayed at the bottom of the scaffold.
2529    ///
2530    /// Typically this is a list of `TextButton` widgets. These buttons are
2531    /// persistently visible, even if the [`body`](Self::body) of the scaffold scrolls.
2532    ///
2533    /// These widgets will be wrapped in an [`OverflowBar`].
2534    ///
2535    /// The [`persistent_footer_buttons`](Self::persistent_footer_buttons) are rendered above
2536    /// the [`bottom_navigation_bar`](Self::bottom_navigation_bar) but below the
2537    /// [`body`](Self::body).
2538    pub persistent_footer_buttons: Option<Vec<WidgetRef>>,
2539
2540    /// The alignment of the [`persistent_footer_buttons`](Self::persistent_footer_buttons)
2541    /// inside the [`OverflowBar`].
2542    ///
2543    /// Defaults to `AlignmentDirectional::CENTER_END`.
2544    pub persistent_footer_alignment: AlignmentDirectional,
2545
2546    /// Decoration for the container that holds the
2547    /// [`persistent_footer_buttons`](Self::persistent_footer_buttons).
2548    ///
2549    /// By default, this container has a top border with a width of 1.0, created by
2550    /// [`Divider::create_border_side`].
2551    ///
2552    /// See also:
2553    ///
2554    ///  * [`persistent_footer_buttons`](Self::persistent_footer_buttons), which defines the
2555    ///    buttons to show in the footer.
2556    ///  * [`persistent_footer_alignment`](Self::persistent_footer_alignment), which defines
2557    ///    the alignment of the footer buttons.
2558    pub persistent_footer_decoration: Option<BoxDecoration>,
2559
2560    /// A panel displayed to the side of the [`body`](Self::body), often hidden on mobile
2561    /// devices. Swipes in from either left-to-right ([`TextDirection::Ltr`]) or
2562    /// right-to-left ([`TextDirection::Rtl`])
2563    ///
2564    /// Typically a `Drawer`.
2565    ///
2566    /// To open the drawer, use the [`ScaffoldState::open_drawer`] function.
2567    ///
2568    /// To close the drawer, use either [`ScaffoldState::close_drawer`], `Navigator.pop`
2569    /// or press the escape key on the keyboard.
2570    pub drawer: Option<WidgetRef>,
2571
2572    /// Optional callback that is called when the [`Scaffold::drawer`] is opened or closed.
2573    pub on_drawer_changed: Option<DrawerCallback>,
2574
2575    /// A panel displayed to the side of the [`body`](Self::body), often hidden on mobile
2576    /// devices. Swipes in from right-to-left ([`TextDirection::Ltr`]) or left-to-right
2577    /// ([`TextDirection::Rtl`])
2578    ///
2579    /// Typically a `Drawer`.
2580    ///
2581    /// To open the drawer, use the [`ScaffoldState::open_end_drawer`] function.
2582    ///
2583    /// To close the drawer, use either [`ScaffoldState::close_end_drawer`], `Navigator.pop`
2584    /// or press the escape key on the keyboard.
2585    pub end_drawer: Option<WidgetRef>,
2586
2587    /// Optional callback that is called when the [`Scaffold::end_drawer`] is opened or
2588    /// closed.
2589    pub on_end_drawer_changed: Option<DrawerCallback>,
2590
2591    /// The color to use for the scrim that obscures primary content while a drawer is open.
2592    ///
2593    /// If this is null, then `DrawerThemeData.scrimColor` is used. If that
2594    /// is also null, then it defaults to `Colors.black54`.
2595    pub drawer_scrim_color: Option<Color>,
2596
2597    /// A builder for the widget that obscures the [`body`](Self::body) when a draggable
2598    /// [`bottom_sheet`](Self::bottom_sheet) covers most of the screen. Dart's default is
2599    /// `_defaultBottomSheetScrimBuilder`.
2600    pub bottom_sheet_scrim_builder: BottomSheetScrimBuilder,
2601
2602    /// The color of the [`Material`] widget that underlies the entire Scaffold.
2603    ///
2604    /// The theme's `ThemeData.scaffoldBackgroundColor` by default.
2605    pub background_color: Option<Color>,
2606
2607    /// A bottom navigation bar to display at the bottom of the scaffold.
2608    ///
2609    /// Snack bars slide from underneath the bottom navigation bar while bottom
2610    /// sheets are stacked on top.
2611    ///
2612    /// The [`bottom_navigation_bar`](Self::bottom_navigation_bar) is rendered below the
2613    /// [`persistent_footer_buttons`](Self::persistent_footer_buttons) and the
2614    /// [`body`](Self::body).
2615    pub bottom_navigation_bar: Option<WidgetRef>,
2616
2617    /// The persistent bottom sheet to display.
2618    ///
2619    /// A persistent bottom sheet shows information that supplements the primary
2620    /// content of the app. A persistent bottom sheet remains visible even when
2621    /// the user interacts with other parts of the app.
2622    ///
2623    /// A closely related widget is a modal bottom sheet, which is an alternative
2624    /// to a menu or a dialog and prevents the user from interacting with the rest
2625    /// of the app. Modal bottom sheets can be created and displayed with the
2626    /// `ShowModalBottomSheet` function.
2627    ///
2628    /// Unlike the persistent bottom sheet displayed by
2629    /// [`ScaffoldState::show_bottom_sheet`], this bottom sheet is not a `LocalHistoryEntry`
2630    /// and cannot be dismissed with the scaffold appbar's back button.
2631    ///
2632    /// If a persistent bottom sheet created with [`ScaffoldState::show_bottom_sheet`]
2633    /// is already visible, it must be closed before building the Scaffold with a new
2634    /// [`bottom_sheet`](Self::bottom_sheet).
2635    ///
2636    /// The value of [`bottom_sheet`](Self::bottom_sheet) can be any widget at all. It's
2637    /// unlikely to actually be a [`BottomSheet`], which is used by the implementations of
2638    /// [`ScaffoldState::show_bottom_sheet`] and `ShowModalBottomSheet`. Typically it's a
2639    /// widget that includes [`Material`].
2640    pub bottom_sheet: Option<WidgetRef>,
2641
2642    /// If true the [`body`](Self::body) and the scaffold's floating widgets should size
2643    /// themselves to avoid the onscreen keyboard whose height is defined by the
2644    /// ambient [`MediaQuery`]'s `MediaQueryData.viewInsets` `bottom` property.
2645    ///
2646    /// For example, if there is an onscreen keyboard displayed above the
2647    /// scaffold, the body can be resized to avoid overlapping the keyboard, which
2648    /// prevents widgets inside the body from being obscured by the keyboard.
2649    ///
2650    /// Defaults to true.
2651    pub resize_to_avoid_bottom_inset: Option<bool>,
2652
2653    /// Whether this scaffold is being displayed at the top of the screen.
2654    ///
2655    /// If true then the height of the `appBar` will be extended by the height
2656    /// of the screen's status bar, i.e. the top padding for [`MediaQuery`].
2657    ///
2658    /// The default value of this property, like the default value of
2659    /// `AppBar.primary`, is true.
2660    pub primary: bool,
2661
2662    /// Determines the way that drag start behavior is handled.
2663    pub drawer_drag_start_behavior: waft_gestures::DragStartBehavior,
2664
2665    /// The width of the area within which a horizontal swipe will open the
2666    /// drawer.
2667    ///
2668    /// By default, the value used is 20.0 added to the padding edge of
2669    /// `MediaQuery.paddingOf(context)` that corresponds to the surrounding
2670    /// [`TextDirection`]. This ensures that the drag area for notched devices is
2671    /// not obscured.
2672    pub drawer_edge_drag_width: Option<f64>,
2673
2674    /// Determines if the [`Scaffold::drawer`] can be opened with a drag
2675    /// gesture on mobile.
2676    ///
2677    /// On desktop platforms, the drawer is not draggable.
2678    ///
2679    /// By default, the drag gesture is enabled on mobile.
2680    pub drawer_enable_open_drag_gesture: bool,
2681
2682    /// Determines if the [`Scaffold::end_drawer`] can be opened with a
2683    /// gesture on mobile.
2684    ///
2685    /// On desktop platforms, the drawer is not draggable.
2686    ///
2687    /// By default, the drag gesture is enabled on mobile.
2688    pub end_drawer_enable_open_drag_gesture: bool,
2689
2690    /// Restoration ID to save and restore the state of the [`Scaffold`].
2691    ///
2692    /// If it is non-null, the scaffold will persist and restore whether the
2693    /// [`drawer`](Self::drawer) and [`end_drawer`](Self::end_drawer) was open or closed.
2694    ///
2695    /// The state of this widget is persisted in a [`RestorationBucket`] claimed
2696    /// from the surrounding `RestorationScope` using the provided restoration ID.
2697    pub restoration_id: Option<String>,
2698}
2699
2700impl Scaffold {
2701    /// Creates a visual scaffold for Material Design widgets.
2702    pub fn new() -> Scaffold {
2703        Scaffold {
2704            key: None,
2705            extend_body: false,
2706            drawer_barrier_dismissible: true,
2707            extend_body_behind_app_bar: false,
2708            app_bar: None,
2709            body: None,
2710            floating_action_button: None,
2711            floating_action_button_location: None,
2712            floating_action_button_animator: None,
2713            persistent_footer_buttons: None,
2714            persistent_footer_alignment: AlignmentDirectional::CENTER_END,
2715            persistent_footer_decoration: None,
2716            drawer: None,
2717            on_drawer_changed: None,
2718            end_drawer: None,
2719            on_end_drawer_changed: None,
2720            drawer_scrim_color: None,
2721            bottom_sheet_scrim_builder: Rc::new(Scaffold::default_bottom_sheet_scrim_builder),
2722            background_color: None,
2723            bottom_navigation_bar: None,
2724            bottom_sheet: None,
2725            resize_to_avoid_bottom_inset: None,
2726            primary: true,
2727            drawer_drag_start_behavior: waft_gestures::DragStartBehavior::Start,
2728            drawer_edge_drag_width: None,
2729            drawer_enable_open_drag_gesture: true,
2730            end_drawer_enable_open_drag_gesture: true,
2731            restoration_id: None,
2732        }
2733    }
2734
2735    /// Dart `Scaffold(key:)`.
2736    pub fn key(mut self, key: KeyRef) -> Scaffold {
2737        self.key = Some(key);
2738        self
2739    }
2740
2741    /// Dart `Scaffold(appBar:)`.
2742    pub fn app_bar(mut self, app_bar: PreferredSizeWidgetRef) -> Scaffold {
2743        self.app_bar = Some(app_bar);
2744        self
2745    }
2746
2747    /// Dart `Scaffold(body:)`.
2748    #[cfg_attr(debug_assertions, track_caller)]
2749    pub fn body<K>(mut self, body: impl IntoWidget<K>) -> Scaffold {
2750        self.body = Some(body.into_widget());
2751        self
2752    }
2753
2754    /// Dart `Scaffold(floatingActionButton:)`.
2755    #[cfg_attr(debug_assertions, track_caller)]
2756    pub fn floating_action_button<K>(
2757        mut self,
2758        floating_action_button: impl IntoWidget<K>,
2759    ) -> Scaffold {
2760        self.floating_action_button = Some(floating_action_button.into_widget());
2761        self
2762    }
2763
2764    /// Dart `Scaffold(floatingActionButtonLocation:)`.
2765    pub fn floating_action_button_location(
2766        mut self,
2767        floating_action_button_location: FloatingActionButtonLocationRef,
2768    ) -> Scaffold {
2769        self.floating_action_button_location = Some(floating_action_button_location);
2770        self
2771    }
2772
2773    /// Dart `Scaffold(floatingActionButtonAnimator:)`.
2774    pub fn floating_action_button_animator(
2775        mut self,
2776        floating_action_button_animator: FloatingActionButtonAnimatorRef,
2777    ) -> Scaffold {
2778        self.floating_action_button_animator = Some(floating_action_button_animator);
2779        self
2780    }
2781
2782    /// Dart `Scaffold(persistentFooterButtons:)`.
2783    pub fn persistent_footer_buttons(
2784        mut self,
2785        persistent_footer_buttons: Vec<WidgetRef>,
2786    ) -> Scaffold {
2787        self.persistent_footer_buttons = Some(persistent_footer_buttons);
2788        self
2789    }
2790
2791    /// Dart `Scaffold(persistentFooterAlignment:)`.
2792    pub fn persistent_footer_alignment(
2793        mut self,
2794        persistent_footer_alignment: AlignmentDirectional,
2795    ) -> Scaffold {
2796        self.persistent_footer_alignment = persistent_footer_alignment;
2797        self
2798    }
2799
2800    /// Dart `Scaffold(persistentFooterDecoration:)`.
2801    pub fn persistent_footer_decoration(
2802        mut self,
2803        persistent_footer_decoration: BoxDecoration,
2804    ) -> Scaffold {
2805        self.persistent_footer_decoration = Some(persistent_footer_decoration);
2806        self
2807    }
2808
2809    /// Dart `Scaffold(drawer:)`.
2810    #[cfg_attr(debug_assertions, track_caller)]
2811    pub fn drawer<K>(mut self, drawer: impl IntoWidget<K>) -> Scaffold {
2812        self.drawer = Some(drawer.into_widget());
2813        self
2814    }
2815
2816    /// Dart `Scaffold(onDrawerChanged:)`.
2817    pub fn on_drawer_changed(
2818        mut self,
2819        on_drawer_changed: impl Fn(&mut App, bool) + 'static,
2820    ) -> Scaffold {
2821        self.on_drawer_changed = Some(Rc::new(on_drawer_changed));
2822        self
2823    }
2824
2825    /// Dart `Scaffold(endDrawer:)`.
2826    #[cfg_attr(debug_assertions, track_caller)]
2827    pub fn end_drawer<K>(mut self, end_drawer: impl IntoWidget<K>) -> Scaffold {
2828        self.end_drawer = Some(end_drawer.into_widget());
2829        self
2830    }
2831
2832    /// Dart `Scaffold(onEndDrawerChanged:)`.
2833    pub fn on_end_drawer_changed(
2834        mut self,
2835        on_end_drawer_changed: impl Fn(&mut App, bool) + 'static,
2836    ) -> Scaffold {
2837        self.on_end_drawer_changed = Some(Rc::new(on_end_drawer_changed));
2838        self
2839    }
2840
2841    /// Dart `Scaffold(bottomNavigationBar:)`.
2842    #[cfg_attr(debug_assertions, track_caller)]
2843    pub fn bottom_navigation_bar<K>(
2844        mut self,
2845        bottom_navigation_bar: impl IntoWidget<K>,
2846    ) -> Scaffold {
2847        self.bottom_navigation_bar = Some(bottom_navigation_bar.into_widget());
2848        self
2849    }
2850
2851    /// Dart `Scaffold(bottomSheet:)`.
2852    #[cfg_attr(debug_assertions, track_caller)]
2853    pub fn bottom_sheet<K>(mut self, bottom_sheet: impl IntoWidget<K>) -> Scaffold {
2854        self.bottom_sheet = Some(bottom_sheet.into_widget());
2855        self
2856    }
2857
2858    /// Dart `Scaffold(backgroundColor:)`.
2859    pub fn background_color(mut self, background_color: Color) -> Scaffold {
2860        self.background_color = Some(background_color);
2861        self
2862    }
2863
2864    /// Dart `Scaffold(resizeToAvoidBottomInset:)`.
2865    pub fn resize_to_avoid_bottom_inset(mut self, resize_to_avoid_bottom_inset: bool) -> Scaffold {
2866        self.resize_to_avoid_bottom_inset = Some(resize_to_avoid_bottom_inset);
2867        self
2868    }
2869
2870    /// Dart `Scaffold(primary:)`.
2871    pub fn primary(mut self, primary: bool) -> Scaffold {
2872        self.primary = primary;
2873        self
2874    }
2875
2876    /// Dart `Scaffold(drawerDragStartBehavior:)`.
2877    pub fn drawer_drag_start_behavior(
2878        mut self,
2879        drawer_drag_start_behavior: waft_gestures::DragStartBehavior,
2880    ) -> Scaffold {
2881        self.drawer_drag_start_behavior = drawer_drag_start_behavior;
2882        self
2883    }
2884
2885    /// Dart `Scaffold(extendBody:)`.
2886    pub fn extend_body(mut self, extend_body: bool) -> Scaffold {
2887        self.extend_body = extend_body;
2888        self
2889    }
2890
2891    /// Dart `Scaffold(drawerBarrierDismissible:)`.
2892    pub fn drawer_barrier_dismissible(mut self, drawer_barrier_dismissible: bool) -> Scaffold {
2893        self.drawer_barrier_dismissible = drawer_barrier_dismissible;
2894        self
2895    }
2896
2897    /// Dart `Scaffold(extendBodyBehindAppBar:)`.
2898    pub fn extend_body_behind_app_bar(mut self, extend_body_behind_app_bar: bool) -> Scaffold {
2899        self.extend_body_behind_app_bar = extend_body_behind_app_bar;
2900        self
2901    }
2902
2903    /// Dart `Scaffold(drawerScrimColor:)`.
2904    pub fn drawer_scrim_color(mut self, drawer_scrim_color: Color) -> Scaffold {
2905        self.drawer_scrim_color = Some(drawer_scrim_color);
2906        self
2907    }
2908
2909    /// Dart `Scaffold(bottomSheetScrimBuilder:)`.
2910    pub fn bottom_sheet_scrim_builder(
2911        mut self,
2912        bottom_sheet_scrim_builder: impl Fn(
2913            &mut App,
2914            BuildContext,
2915            AnimationRef<f64>,
2916        ) -> Option<WidgetRef>
2917        + 'static,
2918    ) -> Scaffold {
2919        self.bottom_sheet_scrim_builder = Rc::new(bottom_sheet_scrim_builder);
2920        self
2921    }
2922
2923    /// Dart `Scaffold(drawerEdgeDragWidth:)`.
2924    pub fn drawer_edge_drag_width(mut self, drawer_edge_drag_width: f64) -> Scaffold {
2925        self.drawer_edge_drag_width = Some(drawer_edge_drag_width);
2926        self
2927    }
2928
2929    /// Dart `Scaffold(drawerEnableOpenDragGesture:)`.
2930    pub fn drawer_enable_open_drag_gesture(
2931        mut self,
2932        drawer_enable_open_drag_gesture: bool,
2933    ) -> Scaffold {
2934        self.drawer_enable_open_drag_gesture = drawer_enable_open_drag_gesture;
2935        self
2936    }
2937
2938    /// Dart `Scaffold(endDrawerEnableOpenDragGesture:)`.
2939    pub fn end_drawer_enable_open_drag_gesture(
2940        mut self,
2941        end_drawer_enable_open_drag_gesture: bool,
2942    ) -> Scaffold {
2943        self.end_drawer_enable_open_drag_gesture = end_drawer_enable_open_drag_gesture;
2944        self
2945    }
2946
2947    /// Dart `Scaffold(restorationId:)`.
2948    pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> Scaffold {
2949        self.restoration_id = Some(restoration_id.into());
2950        self
2951    }
2952
2953    /// Finds the [`ScaffoldState`] from the closest instance of this class that
2954    /// encloses the given context.
2955    ///
2956    /// If no instance of this class encloses the given context, will cause an
2957    /// assert in debug mode, and throw an exception in release mode.
2958    ///
2959    /// This method can be expensive (it walks the element tree).
2960    ///
2961    /// Typical usage of the [`Scaffold::of`] function is to call it from within the
2962    /// `build` method of a child of a [`Scaffold`].
2963    ///
2964    /// When the [`Scaffold`] is actually created in the same `build` function, the
2965    /// `context` argument to the `build` function can't be used to find the
2966    /// [`Scaffold`] (since it's "above" the widget being returned in the widget
2967    /// tree). In such cases, the following technique with a [`Builder`] can be used
2968    /// to provide a new scope with a [`BuildContext`] that is "under" the
2969    /// [`Scaffold`].
2970    ///
2971    /// A more efficient solution is to split your build function into several
2972    /// widgets. This introduces a new context from which you can obtain the
2973    /// [`Scaffold`]. In this solution, you would have an outer widget that creates
2974    /// the [`Scaffold`] populated by instances of your new inner widgets, and then
2975    /// in these inner widgets you would use [`Scaffold::of`].
2976    ///
2977    /// A less elegant but more expedient solution is assign a [`GlobalKey`] to the
2978    /// [`Scaffold`], then use the `key.current_state` method to obtain the
2979    /// [`ScaffoldState`] rather than using the [`Scaffold::of`] function.
2980    ///
2981    /// If there is no [`Scaffold`] in scope, then this will throw an exception.
2982    /// To return null if there is no [`Scaffold`], use [`maybe_of`](Self::maybe_of).
2983    pub fn of(app: &mut App, context: BuildContext) -> Handle<ScaffoldState> {
2984        let result = context.find_ancestor_state_of_type::<ScaffoldState>(app);
2985        if let Some(result) = result {
2986            return result;
2987        }
2988        panic!(
2989            "Scaffold.of() called with a context that does not contain a Scaffold.\n\
2990             No Scaffold ancestor could be found starting from the context that was passed to \
2991             Scaffold.of(). This usually happens when the context provided is from the same \
2992             StatefulWidget as that whose build function actually creates the Scaffold widget \
2993             being sought.\n\
2994             There are several ways to avoid this problem. The simplest is to use a Builder to \
2995             get a context that is \"under\" the Scaffold. For an example of this, please see \
2996             the documentation for Scaffold.of():\n  \
2997             https://api.flutter.dev/flutter/material/Scaffold/of.html\n\
2998             A more efficient solution is to split your build function into several widgets. \
2999             This introduces a new context from which you can obtain the Scaffold. In this \
3000             solution, you would have an outer widget that creates the Scaffold populated by \
3001             instances of your new inner widgets, and then in these inner widgets you would use \
3002             Scaffold.of().\n\
3003             A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, \
3004             then use the key.currentState property to obtain the ScaffoldState rather than \
3005             using the Scaffold.of() function.\n\
3006             The context used was:\n  {}",
3007            context.widget(app).type_name()
3008        );
3009    }
3010
3011    /// Finds the [`ScaffoldState`] from the closest instance of this class that
3012    /// encloses the given context.
3013    ///
3014    /// If no instance of this class encloses the given context, will return `None`.
3015    /// To throw an exception instead, use [`of`](Self::of) instead of this function.
3016    ///
3017    /// This method can be expensive (it walks the element tree).
3018    ///
3019    /// See also:
3020    ///
3021    ///  * [`of`](Self::of), a similar function to this one that throws if no instance
3022    ///    encloses the given context. Also includes some sample code in its
3023    ///    documentation.
3024    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<Handle<ScaffoldState>> {
3025        context.find_ancestor_state_of_type::<ScaffoldState>(app)
3026    }
3027
3028    /// Returns a notifier of the [`ScaffoldGeometry`] for the [`Scaffold`] that encloses
3029    /// the given context.
3030    ///
3031    /// The geometry notifier is a [`ChangeNotifier`] whose
3032    /// [`value`](ScaffoldGeometryNotifier::value) is the [`ScaffoldGeometry`] of the closest
3033    /// [`Scaffold`] ancestor of the given context; read it only while painting.
3034    ///
3035    /// This method can be expensive (it walks the element tree).
3036    ///
3037    /// For an example of using this, see the `BottomAppBar`, which uses it to paint a notch
3038    /// around the `FloatingActionButton`.
3039    ///
3040    /// # Panics
3041    ///
3042    /// If no [`Scaffold`] encloses `context`.
3043    pub fn geometry_of(app: &mut App, context: BuildContext) -> Ref<ScaffoldGeometryNotifier> {
3044        let scaffold_scope =
3045            ScaffoldScope::inherit_from(app, context, Some(ScaffoldAspect::Geometry));
3046        match scaffold_scope {
3047            Some(scaffold_scope) => scaffold_scope.geometry_notifier.clone(),
3048            None => panic!(
3049                "Scaffold.geometryOf() called with a context that does not contain a Scaffold.\n\
3050                 This usually happens when the context provided is from the same StatefulWidget \
3051                 as that whose build function actually creates the Scaffold widget being \
3052                 sought.\n\
3053                 There are several ways to avoid this problem. The simplest is to use a Builder \
3054                 to get a context that is \"under\" the Scaffold. For an example of this, please \
3055                 see the documentation for Scaffold.of():\n  \
3056                 https://api.flutter.dev/flutter/material/Scaffold/of.html\n\
3057                 A more efficient solution is to split your build function into several \
3058                 widgets. This introduces a new context from which you can obtain the Scaffold. \
3059                 In this solution, you would have an outer widget that creates the Scaffold \
3060                 populated by instances of your new inner widgets, and then in these inner \
3061                 widgets you would use Scaffold.geometryOf().\n\
3062                 The context used was:\n  {}",
3063                context.widget(app).type_name()
3064            ),
3065        }
3066    }
3067
3068    /// Whether the Scaffold that most tightly encloses the given context has a
3069    /// drawer.
3070    ///
3071    /// If this is being used during a build (for example to decide whether to
3072    /// show an "open drawer" button), set the `register_for_updates` argument to
3073    /// true. This will then set up an `InheritedWidget` relationship with the
3074    /// [`Scaffold`] so that the client widget gets rebuilt whenever the
3075    /// [`has_drawer`](Self::has_drawer) value changes.
3076    ///
3077    /// Dart's default `register_for_updates` is true.
3078    ///
3079    /// See also:
3080    ///
3081    ///  * [`Scaffold::of`], which provides access to the [`ScaffoldState`] object as a
3082    ///    whole, from which you can show bottom sheets, and so forth.
3083    ///  * [`ScaffoldState::open_drawer`] and [`ScaffoldState::open_end_drawer`],
3084    ///    which open the drawer.
3085    pub fn has_drawer(app: &mut App, context: BuildContext, register_for_updates: bool) -> bool {
3086        if register_for_updates {
3087            let scaffold =
3088                ScaffoldScope::inherit_from(app, context, Some(ScaffoldAspect::HasDrawer));
3089            scaffold.is_some_and(|scaffold| scaffold.has_drawer)
3090        } else {
3091            let scaffold = context.find_ancestor_state_of_type::<ScaffoldState>(app);
3092            scaffold.is_some_and(|scaffold| scaffold.has_drawer(app))
3093        }
3094    }
3095
3096    fn default_bottom_sheet_scrim_builder(
3097        _app: &mut App,
3098        _context: BuildContext,
3099        animation: AnimationRef<f64>,
3100    ) -> Option<WidgetRef> {
3101        Some(
3102            ListenableBuilder::new(Rc::new(animation.clone()), move |app, _context, _child| {
3103                let extent_remaining =
3104                    K_BOTTOM_SHEET_DOMINATES_PERCENTAGE * (1.0 - animation.value(app));
3105                let floating_button_visibility_value =
3106                    extent_remaining * K_BOTTOM_SHEET_DOMINATES_PERCENTAGE * 10.0;
3107
3108                let opacity = f64::max(
3109                    K_MIN_BOTTOM_SHEET_SCRIM_OPACITY,
3110                    K_MAX_BOTTOM_SHEET_SCRIM_OPACITY - floating_button_visibility_value,
3111                );
3112
3113                #[expect(deprecated, reason = "Dart calls the deprecated `withOpacity`")]
3114                let color = Colors::BLACK.with_opacity(opacity);
3115                ModalBarrier::new()
3116                    .dismissible(false)
3117                    .color(color)
3118                    .into_widget()
3119            })
3120            .into_widget(),
3121        )
3122    }
3123}
3124
3125impl Default for Scaffold {
3126    fn default() -> Scaffold {
3127        Scaffold::new()
3128    }
3129}
3130
3131impl Debug for Scaffold {
3132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3133        f.debug_struct("Scaffold")
3134            .field("appBar", &self.app_bar)
3135            .field("body", &self.body)
3136            .field("floatingActionButton", &self.floating_action_button)
3137            .field("drawer", &self.drawer)
3138            .field("endDrawer", &self.end_drawer)
3139            .field("bottomNavigationBar", &self.bottom_navigation_bar)
3140            .field("bottomSheet", &self.bottom_sheet)
3141            .finish_non_exhaustive()
3142    }
3143}
3144
3145impl StatefulWidget for Scaffold {
3146    type State = ScaffoldState;
3147
3148    fn key(&self) -> Option<&KeyRef> {
3149        self.key.as_ref()
3150    }
3151
3152    fn create_state(&self) -> ScaffoldState {
3153        ScaffoldState {
3154            state: StateData::new(),
3155            ticker_provider: TickerProviderStateMixinData::new(),
3156            restoration: RestorationMixinData::new(),
3157            observer: None,
3158            drawer_key: GlobalKey::new(),
3159            end_drawer_key: GlobalKey::new(),
3160            body_key: GlobalKey::new(),
3161            status_bar_key: GlobalKey::new(),
3162            app_bar_max_height: None,
3163            drawer_opened: None,
3164            end_drawer_opened: None,
3165            scaffold_messenger: None,
3166            messenger_snack_bar: None,
3167            messenger_material_banner: None,
3168            dismissed_bottom_sheets: Vec::new(),
3169            current_bottom_sheet: None,
3170            current_bottom_sheet_key: GlobalKey::new(),
3171            persistent_sheet_history_entry: None,
3172            floating_action_button_move_controller: None,
3173            floating_action_button_animator: None,
3174            previous_floating_action_button_location: None,
3175            floating_action_button_location: None,
3176            floating_action_button_visibility_controller: None,
3177            geometry_notifier: None,
3178            bottom_sheet_scrim_animation_controller: None,
3179            show_body_scrim: false,
3180        }
3181    }
3182}
3183
3184/// State for a [`Scaffold`].
3185///
3186/// Can display [`BottomSheet`]s. Retrieve a [`ScaffoldState`] from the current
3187/// [`BuildContext`] using [`Scaffold::of`].
3188pub struct ScaffoldState {
3189    state: StateData<Scaffold>,
3190    ticker_provider: TickerProviderStateMixinData,
3191    restoration: RestorationMixinData,
3192    /// The `WidgetsBindingObserver` this state registers: an `Rc` of its own handle, made once.
3193    observer: Option<WidgetsBindingObserverRef>,
3194
3195    // DRAWER API
3196    /// Dart's `GlobalKey<DrawerControllerState>`.
3197    drawer_key: GlobalKey,
3198    /// Dart's `GlobalKey<DrawerControllerState>`.
3199    end_drawer_key: GlobalKey,
3200
3201    body_key: GlobalKey,
3202    status_bar_key: GlobalKey,
3203
3204    app_bar_max_height: Option<f64>,
3205
3206    /// Dart's `final RestorableBool _drawerOpened = RestorableBool(false)`, made in
3207    /// `init_state` because a property is an arena object.
3208    drawer_opened: Option<Ref<RestorableBool>>,
3209    /// Dart's `_endDrawerOpened`, made in `init_state`.
3210    end_drawer_opened: Option<Ref<RestorableBool>>,
3211
3212    // Used for both the snackbar and material banner APIs
3213    scaffold_messenger: Option<Handle<ScaffoldMessengerState>>,
3214
3215    // SNACKBAR API
3216    messenger_snack_bar: Option<Rc<ScaffoldFeatureController<SnackBar, SnackBarClosedReason>>>,
3217
3218    // MATERIAL BANNER API
3219
3220    // The _messengerMaterialBanner represents the current MaterialBanner being managed by
3221    // the ScaffoldMessenger, instead of the Scaffold.
3222    messenger_material_banner:
3223        Option<Rc<ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>>>,
3224
3225    // PERSISTENT BOTTOM SHEET API
3226
3227    // Contains bottom sheets that may still be animating out of view.
3228    // Important if the app/user takes an action that could repeatedly show a
3229    // bottom sheet.
3230    /// Dart's `List<_StandardBottomSheet>`, compared by identity.
3231    dismissed_bottom_sheets: Vec<WidgetRef>,
3232    current_bottom_sheet: Option<Rc<PersistentBottomSheetController>>,
3233    current_bottom_sheet_key: GlobalKey,
3234    persistent_sheet_history_entry: Option<Ref<LocalHistoryEntry>>,
3235
3236    // Floating Action Button API
3237    floating_action_button_move_controller: Option<Ref<AnimationController>>,
3238    floating_action_button_animator: Option<FloatingActionButtonAnimatorRef>,
3239    previous_floating_action_button_location: Option<FloatingActionButtonLocationRef>,
3240    floating_action_button_location: Option<FloatingActionButtonLocationRef>,
3241
3242    floating_action_button_visibility_controller: Option<Ref<AnimationController>>,
3243
3244    // INTERNALS
3245    geometry_notifier: Option<Ref<ScaffoldGeometryNotifier>>,
3246
3247    bottom_sheet_scrim_animation_controller: Option<Ref<AnimationController>>,
3248    show_body_scrim: bool,
3249}
3250
3251impl ScaffoldState {
3252    // DRAWER API
3253
3254    /// Whether this scaffold has a non-null [`Scaffold::app_bar`].
3255    pub fn has_app_bar(self: Handle<Self>, app: &App) -> bool {
3256        self.widget(app).app_bar.is_some()
3257    }
3258
3259    /// Whether this scaffold has a non-null [`Scaffold::drawer`].
3260    pub fn has_drawer(self: Handle<Self>, app: &App) -> bool {
3261        self.widget(app).drawer.is_some()
3262    }
3263
3264    /// Whether this scaffold has a non-null [`Scaffold::end_drawer`].
3265    pub fn has_end_drawer(self: Handle<Self>, app: &App) -> bool {
3266        self.widget(app).end_drawer.is_some()
3267    }
3268
3269    /// Whether this scaffold has a non-null [`Scaffold::floating_action_button`].
3270    pub fn has_floating_action_button(self: Handle<Self>, app: &App) -> bool {
3271        self.widget(app).floating_action_button.is_some()
3272    }
3273
3274    /// The max height the [`Scaffold::app_bar`] uses.
3275    ///
3276    /// This is based on the appBar preferred height plus the top padding.
3277    pub fn app_bar_max_height(self: Handle<Self>, app: &App) -> Option<f64> {
3278        app.get(self).app_bar_max_height
3279    }
3280
3281    fn drawer_opened(self: Handle<Self>, app: &App) -> Handle<RestorableBool> {
3282        app.get(self)
3283            .drawer_opened
3284            .handle()
3285            .expect("made in init_state")
3286    }
3287
3288    fn end_drawer_opened(self: Handle<Self>, app: &App) -> Handle<RestorableBool> {
3289        app.get(self)
3290            .end_drawer_opened
3291            .handle()
3292            .expect("made in init_state")
3293    }
3294
3295    /// Whether the [`Scaffold::drawer`] is opened.
3296    ///
3297    /// See also:
3298    ///
3299    ///  * [`ScaffoldState::open_drawer`], which opens the [`Scaffold::drawer`] of a
3300    ///    [`Scaffold`].
3301    pub fn is_drawer_open(self: Handle<Self>, app: &App) -> bool {
3302        *RestorableValue::value(self.drawer_opened(app), app)
3303    }
3304
3305    /// Whether the drawer's barrier can be dismissed by tapping on it.
3306    pub fn is_drawer_barrier_dismissible(self: Handle<Self>, app: &App) -> bool {
3307        self.widget(app).drawer_barrier_dismissible
3308    }
3309
3310    /// Whether the [`Scaffold::end_drawer`] is opened.
3311    ///
3312    /// See also:
3313    ///
3314    ///  * [`ScaffoldState::open_end_drawer`], which opens the [`Scaffold::end_drawer`] of a
3315    ///    [`Scaffold`].
3316    pub fn is_end_drawer_open(self: Handle<Self>, app: &App) -> bool {
3317        *RestorableValue::value(self.end_drawer_opened(app), app)
3318    }
3319
3320    fn drawer_opened_callback(self: Handle<Self>, app: &mut App, is_opened: bool) {
3321        let drawer_key = app.get(self).drawer_key.clone();
3322        if self.is_drawer_open(app) != is_opened
3323            && drawer_key
3324                .current_state::<DrawerControllerState>(app)
3325                .is_some()
3326        {
3327            RestorableValue::set_value(self.drawer_opened(app), app, is_opened);
3328            self.set_state(app, |_| {});
3329            if let Some(on_drawer_changed) = self.widget(app).on_drawer_changed.clone() {
3330                on_drawer_changed(app, is_opened);
3331            }
3332        }
3333    }
3334
3335    fn end_drawer_opened_callback(self: Handle<Self>, app: &mut App, is_opened: bool) {
3336        let end_drawer_key = app.get(self).end_drawer_key.clone();
3337        if self.is_end_drawer_open(app) != is_opened
3338            && end_drawer_key
3339                .current_state::<DrawerControllerState>(app)
3340                .is_some()
3341        {
3342            RestorableValue::set_value(self.end_drawer_opened(app), app, is_opened);
3343            self.set_state(app, |_| {});
3344            if let Some(on_end_drawer_changed) = self.widget(app).on_end_drawer_changed.clone() {
3345                on_end_drawer_changed(app, is_opened);
3346            }
3347        }
3348    }
3349
3350    /// Opens the [`Drawer`](crate::Drawer) (if any).
3351    ///
3352    /// If the scaffold has a non-null [`Scaffold::drawer`], this function will cause
3353    /// the drawer to begin its entrance animation.
3354    ///
3355    /// Normally this is not needed since the [`Scaffold`] automatically shows an
3356    /// appropriate `IconButton`, and handles the edge-swipe gesture, to show the
3357    /// drawer.
3358    ///
3359    /// To close the drawer, use either [`ScaffoldState::close_drawer`] or
3360    /// `Navigator.pop`.
3361    pub fn open_drawer(self: Handle<Self>, app: &mut App) {
3362        let end_drawer_key = app.get(self).end_drawer_key.clone();
3363        if let Some(end_drawer) = end_drawer_key.current_state::<DrawerControllerState>(app)
3364            && self.is_end_drawer_open(app)
3365        {
3366            end_drawer.close(app);
3367        }
3368        let drawer_key = app.get(self).drawer_key.clone();
3369        if let Some(drawer) = drawer_key.current_state::<DrawerControllerState>(app) {
3370            drawer.open(app);
3371        }
3372    }
3373
3374    /// Opens the end side [`Drawer`](crate::Drawer) (if any).
3375    ///
3376    /// If the scaffold has a non-null [`Scaffold::end_drawer`], this function will cause
3377    /// the end side drawer to begin its entrance animation.
3378    ///
3379    /// Normally this is not needed since the [`Scaffold`] automatically shows an
3380    /// appropriate `IconButton`, and handles the edge-swipe gesture, to show the
3381    /// drawer.
3382    ///
3383    /// To close the end side drawer, use either [`ScaffoldState::close_end_drawer`] or
3384    /// `Navigator.pop`.
3385    pub fn open_end_drawer(self: Handle<Self>, app: &mut App) {
3386        let drawer_key = app.get(self).drawer_key.clone();
3387        if let Some(drawer) = drawer_key.current_state::<DrawerControllerState>(app)
3388            && self.is_drawer_open(app)
3389        {
3390            drawer.close(app);
3391        }
3392        let end_drawer_key = app.get(self).end_drawer_key.clone();
3393        if let Some(end_drawer) = end_drawer_key.current_state::<DrawerControllerState>(app) {
3394            end_drawer.open(app);
3395        }
3396    }
3397
3398    // This is used to update the _messengerSnackBar by the ScaffoldMessenger.
3399    fn update_snack_bar(self: Handle<Self>, app: &mut App) {
3400        let scaffold_messenger = app
3401            .get(self)
3402            .scaffold_messenger
3403            .expect("a registered scaffold has a messenger");
3404        let messenger_snack_bar = app.get(scaffold_messenger).snack_bars.front().cloned();
3405
3406        if !option_rc_ptr_eq(&app.get(self).messenger_snack_bar, &messenger_snack_bar) {
3407            self.set_state(app, move |state| {
3408                state.messenger_snack_bar = messenger_snack_bar;
3409            });
3410        }
3411    }
3412
3413    // This is used to update the _messengerMaterialBanner by the ScaffoldMessenger.
3414    fn update_material_banner(self: Handle<Self>, app: &mut App) {
3415        let scaffold_messenger = app
3416            .get(self)
3417            .scaffold_messenger
3418            .expect("a registered scaffold has a messenger");
3419        let messenger_material_banner = app
3420            .get(scaffold_messenger)
3421            .material_banners
3422            .front()
3423            .cloned();
3424
3425        if !option_rc_ptr_eq(
3426            &app.get(self).messenger_material_banner,
3427            &messenger_material_banner,
3428        ) {
3429            self.set_state(app, move |state| {
3430                state.messenger_material_banner = messenger_material_banner;
3431            });
3432        }
3433    }
3434
3435    // PERSISTENT BOTTOM SHEET API
3436
3437    fn maybe_build_persistent_bottom_sheet(self: Handle<Self>, app: &mut App) {
3438        if self.widget(app).bottom_sheet.is_some() && app.get(self).current_bottom_sheet.is_none() {
3439            // The new _currentBottomSheet is not a local history entry so a "back" button
3440            // will not be added to the Scaffold's appbar and the bottom sheet will not
3441            // support drag or swipe to dismiss.
3442            let animation_controller = BottomSheet::create_animation_controller(app, self, None);
3443            animation_controller.set_value(app, 1.0);
3444            let persistent_bottom_sheet_extent_changed =
3445                move |app: &mut App, notification: &DraggableScrollableNotification| -> bool {
3446                    if notification.extent - notification.initial_extent > PRECISION_ERROR_TOLERANCE
3447                    {
3448                        if app.get(self).persistent_sheet_history_entry.is_none() {
3449                            let notification_context = notification.context;
3450                            let entry = LocalHistoryEntry::new(app).on_remove(
3451                                app,
3452                                Listener::new(move |app| {
3453                                    DraggableScrollableActuator::reset(app, notification_context);
3454                                    self.show_body_scrim(app, false, 0.0);
3455                                    self.floating_action_button_visibility_controller(app)
3456                                        .set_value(app, 1.0);
3457                                    app.get_mut(self).persistent_sheet_history_entry = None;
3458                                }),
3459                            );
3460                            app.get_mut(self).persistent_sheet_history_entry = Some(entry.clone());
3461                            let context = self.context(app);
3462                            AnyModalRoute::of(app, context)
3463                                .expect("a persistent bottom sheet inside a modal route")
3464                                .add_local_history_entry(app, entry);
3465                        }
3466                    } else if let Some(entry) =
3467                        app.get(self).persistent_sheet_history_entry.handle()
3468                    {
3469                        entry.remove(app);
3470                    }
3471                    false
3472                };
3473
3474            // Stop the animation and unmount the dismissed sheets from the tree immediately,
3475            // otherwise may cause duplicate GlobalKey assertion if the sheet sub-tree contains
3476            // GlobalKey widgets.
3477            if !app.get(self).dismissed_bottom_sheets.is_empty() {
3478                let sheets = app.get(self).dismissed_bottom_sheets.clone();
3479                for sheet in sheets {
3480                    let animation_controller = downcast_widget::<StandardBottomSheet>(&*sheet)
3481                        .expect("a dismissed sheet is a standard bottom sheet")
3482                        .animation_controller
3483                        .clone();
3484                    animation_controller.reset(app);
3485                }
3486                debug_assert!(app.get(self).dismissed_bottom_sheets.is_empty());
3487            }
3488
3489            let current_bottom_sheet_key = app.get(self).current_bottom_sheet_key.clone();
3490            let persistent_bottom_sheet_extent_changed =
3491                Rc::new(persistent_bottom_sheet_extent_changed);
3492            let builder: WidgetBuilder = Rc::new(move |_app, _context| {
3493                let persistent_bottom_sheet_extent_changed =
3494                    Rc::clone(&persistent_bottom_sheet_extent_changed);
3495                NotificationListener::<DraggableScrollableNotification>::new(
3496                    DraggableScrollableActuator::new(
3497                        StatefulBuilder::new(move |app, _context, _set_state| {
3498                            self.widget(app)
3499                                .bottom_sheet
3500                                .clone()
3501                                .unwrap_or_else(|| SizedBox::shrink().into_widget())
3502                        })
3503                        .key(current_bottom_sheet_key.clone().into()),
3504                    ),
3505                )
3506                .on_notification(move |app, notification| {
3507                    persistent_bottom_sheet_extent_changed(app, notification)
3508                })
3509                .into_widget()
3510            });
3511            let current_bottom_sheet = self.build_bottom_sheet(
3512                app,
3513                builder,
3514                true,
3515                animation_controller.clone(),
3516                BottomSheetOptions::default(),
3517            );
3518            app.get_mut(self).current_bottom_sheet = Some(current_bottom_sheet);
3519        }
3520    }
3521
3522    fn close_current_bottom_sheet(self: Handle<Self>, app: &mut App) {
3523        if let Some(current_bottom_sheet) = app.get(self).current_bottom_sheet.clone() {
3524            if !current_bottom_sheet.is_local_history_entry {
3525                (current_bottom_sheet.feature.close)(app);
3526            }
3527            if cfg!(debug_assertions)
3528                && let Some(current_bottom_sheet) = app.get(self).current_bottom_sheet.clone()
3529            {
3530                current_bottom_sheet
3531                    .feature
3532                    .completer
3533                    .future()
3534                    .then(app, move |app, ()| {
3535                        debug_assert!(app.get(self).current_bottom_sheet.is_none());
3536                    });
3537            }
3538        }
3539    }
3540
3541    /// Closes [`Scaffold::drawer`] if it is currently opened.
3542    ///
3543    /// See [`ScaffoldState::open_drawer`] to open the [`Scaffold::drawer`].
3544    pub fn close_drawer(self: Handle<Self>, app: &mut App) {
3545        if self.has_drawer(app) && self.is_drawer_open(app) {
3546            let drawer_key = app.get(self).drawer_key.clone();
3547            drawer_key
3548                .current_state::<DrawerControllerState>(app)
3549                .expect("an open drawer is mounted")
3550                .close(app);
3551        }
3552    }
3553
3554    /// Closes [`Scaffold::end_drawer`] if it is currently opened.
3555    ///
3556    /// See [`ScaffoldState::open_end_drawer`] to open the [`Scaffold::end_drawer`].
3557    pub fn close_end_drawer(self: Handle<Self>, app: &mut App) {
3558        if self.has_end_drawer(app) && self.is_end_drawer_open(app) {
3559            let end_drawer_key = app.get(self).end_drawer_key.clone();
3560            end_drawer_key
3561                .current_state::<DrawerControllerState>(app)
3562                .expect("an open drawer is mounted")
3563                .close(app);
3564        }
3565    }
3566
3567    fn update_persistent_bottom_sheet(self: Handle<Self>, app: &mut App) {
3568        let current_bottom_sheet_key = app.get(self).current_bottom_sheet_key.clone();
3569        current_bottom_sheet_key
3570            .current_state::<StatefulBuilderState>(app)
3571            .expect("the persistent bottom sheet is mounted")
3572            .set_state(app, |_| {});
3573    }
3574
3575    fn build_bottom_sheet(
3576        self: Handle<Self>,
3577        app: &mut App,
3578        builder: WidgetBuilder,
3579        is_persistent: bool,
3580        animation_controller: Ref<AnimationController>,
3581        options: BottomSheetOptions,
3582    ) -> Rc<PersistentBottomSheetController> {
3583        debug_assert!(
3584            !(self.widget(app).bottom_sheet.is_some()
3585                && is_persistent
3586                && app.get(self).current_bottom_sheet.is_some()),
3587            "Scaffold.bottomSheet cannot be specified while a bottom sheet \
3588             displayed with showBottomSheet() is still visible.\n\
3589             Rebuild the Scaffold with a null bottomSheet before calling showBottomSheet()."
3590        );
3591
3592        let completer = Completer::<()>::new();
3593        let bottom_sheet_key = GlobalKey::new();
3594        // Dart's `late _StandardBottomSheet bottomSheet`, read by the closures below. They are
3595        // kept inside the sheet and its history entry, so they name it weakly: a strong `Rc`
3596        // would make a ring with the sheet, which Dart's collector frees and nothing here does.
3597        let bottom_sheet: Rc<std::cell::OnceCell<Weak<dyn Widget>>> =
3598            Rc::new(std::cell::OnceCell::new());
3599
3600        let removed_entry = Rc::new(Cell::new(false));
3601        let doing_dispose = Rc::new(Cell::new(false));
3602
3603        let remove_persistent_sheet_history_entry_if_needed = move |app: &mut App| {
3604            debug_assert!(is_persistent);
3605            if let Some(entry) = app.get(self).persistent_sheet_history_entry.handle() {
3606                entry.remove(app);
3607                app.get_mut(self).persistent_sheet_history_entry = None;
3608            }
3609        };
3610
3611        let remove_current_bottom_sheet: VoidCallback = Rc::new({
3612            let removed_entry = Rc::clone(&removed_entry);
3613            let bottom_sheet = Rc::clone(&bottom_sheet);
3614            let bottom_sheet_key = bottom_sheet_key.clone();
3615            let completer = completer.clone();
3616            let animation_controller = animation_controller.clone();
3617            move |app: &mut App| {
3618                removed_entry.set(true);
3619                let Some(current_bottom_sheet) = app.get(self).current_bottom_sheet.clone() else {
3620                    return;
3621                };
3622                let bottom_sheet = bottom_sheet
3623                    .get()
3624                    .and_then(Weak::upgrade)
3625                    .expect("built below, and the current sheet keeps it");
3626                debug_assert!(Rc::ptr_eq(
3627                    &current_bottom_sheet.feature.widget,
3628                    &bottom_sheet
3629                ));
3630                debug_assert!(
3631                    bottom_sheet_key
3632                        .current_state::<StandardBottomSheetState>(app)
3633                        .is_some()
3634                );
3635                self.show_floating_action_button(app);
3636
3637                if is_persistent {
3638                    remove_persistent_sheet_history_entry_if_needed(app);
3639                }
3640
3641                bottom_sheet_key
3642                    .current_state::<StandardBottomSheetState>(app)
3643                    .expect("checked above")
3644                    .close(app);
3645                app.get_mut(self).show_body_scrim = false;
3646                self.bottom_sheet_scrim_animation_controller(app)
3647                    .set_value(app, 0.0);
3648                self.set_state(app, |state| {
3649                    state.current_bottom_sheet = None;
3650                });
3651
3652                if !animation_controller.is_dismissed(app) {
3653                    app.get_mut(self).dismissed_bottom_sheets.push(bottom_sheet);
3654                }
3655                completer.complete(app, ());
3656            }
3657        });
3658
3659        let entry = if is_persistent {
3660            None
3661        } else {
3662            let removed_entry = Rc::clone(&removed_entry);
3663            let doing_dispose = Rc::clone(&doing_dispose);
3664            let bottom_sheet = Rc::clone(&bottom_sheet);
3665            let remove_current_bottom_sheet = Rc::clone(&remove_current_bottom_sheet);
3666            Some(LocalHistoryEntry::new(app).on_remove(
3667                app,
3668                Listener::new(move |app| {
3669                    let current_is_this_sheet = app
3670                        .get(self)
3671                        .current_bottom_sheet
3672                        .as_ref()
3673                        .is_some_and(|current| {
3674                            bottom_sheet.get().is_some_and(|sheet| {
3675                                Weak::ptr_eq(&Rc::downgrade(&current.feature.widget), sheet)
3676                            })
3677                        });
3678                    if !removed_entry.get() && current_is_this_sheet && !doing_dispose.get() {
3679                        remove_current_bottom_sheet(app);
3680                    }
3681                }),
3682            ))
3683        };
3684
3685        let remove_entry_if_needed = {
3686            let removed_entry = Rc::clone(&removed_entry);
3687            let entry = entry.clone();
3688            Rc::new(move |app: &mut App| {
3689                if !is_persistent && !removed_entry.get() {
3690                    debug_assert!(entry.is_some());
3691                    entry.as_ref().expect("not persistent").remove(app);
3692                    removed_entry.set(true);
3693                }
3694            })
3695        };
3696
3697        let dispose_controller = animation_controller.clone();
3698        let sheet: WidgetRef = StandardBottomSheet {
3699            key: bottom_sheet_key.clone().into(),
3700            animation_controller,
3701            enable_drag: options.enable_drag.unwrap_or(!is_persistent),
3702            show_drag_handle: options.show_drag_handle,
3703            on_closing: Some(Rc::new({
3704                let bottom_sheet = Rc::clone(&bottom_sheet);
3705                let remove_entry_if_needed = Rc::clone(&remove_entry_if_needed);
3706                move |app: &mut App| {
3707                    let Some(current_bottom_sheet) = app.get(self).current_bottom_sheet.clone()
3708                    else {
3709                        return;
3710                    };
3711                    debug_assert!(bottom_sheet.get().is_some_and(|sheet| Weak::ptr_eq(
3712                        &Rc::downgrade(&current_bottom_sheet.feature.widget),
3713                        sheet
3714                    )));
3715                    remove_entry_if_needed(app);
3716                }
3717            })),
3718            on_dismissed: Some(Rc::new({
3719                let bottom_sheet = Rc::clone(&bottom_sheet);
3720                move |app: &mut App| {
3721                    let sheet = bottom_sheet.get().expect("built below");
3722                    let position = app
3723                        .get(self)
3724                        .dismissed_bottom_sheets
3725                        .iter()
3726                        .position(|dismissed| Weak::ptr_eq(&Rc::downgrade(dismissed), sheet));
3727                    if let Some(position) = position {
3728                        self.set_state(app, |state| {
3729                            state.dismissed_bottom_sheets.remove(position);
3730                        });
3731                    }
3732                }
3733            })),
3734            on_dispose: Some(Rc::new({
3735                let doing_dispose = Rc::clone(&doing_dispose);
3736                let remove_entry_if_needed = Rc::clone(&remove_entry_if_needed);
3737                let should_dispose_animation_controller =
3738                    options.should_dispose_animation_controller;
3739                move |app: &mut App| {
3740                    doing_dispose.set(true);
3741                    remove_entry_if_needed(app);
3742                    if should_dispose_animation_controller {
3743                        dispose_controller.dispose(app);
3744                    }
3745                }
3746            })),
3747            builder,
3748            is_persistent,
3749            background_color: options.background_color,
3750            elevation: options.elevation,
3751            shape: options.shape,
3752            clip_behavior: options.clip_behavior,
3753            constraints: options.constraints,
3754        }
3755        .into_widget();
3756        assert!(bottom_sheet.set(Rc::downgrade(&sheet)).is_ok());
3757
3758        if !is_persistent {
3759            let context = self.context(app);
3760            AnyModalRoute::of(app, context)
3761                .expect("a bottom sheet inside a modal route")
3762                .add_local_history_entry(app, entry.clone().expect("not persistent"));
3763        }
3764
3765        let close: VoidCallback = match entry {
3766            Some(entry) => Rc::new(move |app: &mut App| entry.remove(app)),
3767            None => remove_current_bottom_sheet,
3768        };
3769        let set_state: StateSetter = Rc::new(move |app: &mut App, f: &mut dyn FnMut(&mut App)| {
3770            if let Some(state) = bottom_sheet_key.current_state::<StandardBottomSheetState>(app) {
3771                f(app);
3772                state.set_state(app, |_| {});
3773            }
3774        });
3775        Rc::new(PersistentBottomSheetController {
3776            feature: ScaffoldFeatureController {
3777                widget: sheet,
3778                completer,
3779                close,
3780                set_state: Some(set_state),
3781                _widget_type: PhantomData,
3782            },
3783            is_local_history_entry: !is_persistent,
3784        })
3785    }
3786
3787    /// Shows a Material Design bottom sheet in the nearest [`Scaffold`]. To show
3788    /// a persistent bottom sheet, use the [`Scaffold::bottom_sheet`].
3789    ///
3790    /// Returns a controller that can be used to close and otherwise manipulate the
3791    /// bottom sheet.
3792    ///
3793    /// To rebuild the bottom sheet (e.g. if it is stateful), call
3794    /// [`PersistentBottomSheetController::set_state`] on the controller returned by
3795    /// this method.
3796    ///
3797    /// The new bottom sheet becomes a `LocalHistoryEntry` for the enclosing
3798    /// `ModalRoute` and a back button is added to the app bar of the [`Scaffold`]
3799    /// that closes the bottom sheet.
3800    ///
3801    /// The `transition_animation_controller` controls the bottom sheet's entrance and
3802    /// exit animations. It's up to the owner of the controller to call
3803    /// [`AnimationController::dispose`] when the controller is no longer needed.
3804    ///
3805    /// To create a persistent bottom sheet that is not a `LocalHistoryEntry` and
3806    /// does not add a back button to the enclosing Scaffold's app bar, use the
3807    /// [`Scaffold::bottom_sheet`] constructor parameter.
3808    ///
3809    /// A persistent bottom sheet shows information that supplements the primary
3810    /// content of the app. A persistent bottom sheet remains visible even when
3811    /// the user interacts with other parts of the app.
3812    ///
3813    /// A closely related widget is a modal bottom sheet, which is an alternative
3814    /// to a menu or a dialog and prevents the user from interacting with the rest
3815    /// of the app. Modal bottom sheets can be created and displayed with the
3816    /// `ShowModalBottomSheet` function.
3817    ///
3818    /// The `sheet_animation_style` parameter is used to override the bottom sheet
3819    /// animation duration and reverse animation duration.
3820    ///
3821    /// If [`AnimationStyle::duration`] is provided, it will be used to override
3822    /// the bottom sheet animation duration in the underlying
3823    /// [`BottomSheet::create_animation_controller`].
3824    ///
3825    /// If [`AnimationStyle::reverse_duration`] is provided, it will be used to
3826    /// override the bottom sheet reverse animation duration in the underlying
3827    /// [`BottomSheet::create_animation_controller`].
3828    ///
3829    /// To disable the bottom sheet animation, use `AnimationStyle::no_animation()`.
3830    ///
3831    /// See also:
3832    ///
3833    ///  * [`BottomSheet`], which becomes the parent of the widget returned by the
3834    ///    `builder`.
3835    ///  * `ShowBottomSheet`, which calls this method given a [`BuildContext`].
3836    ///  * `ShowModalBottomSheet`, which can be used to display a modal bottom
3837    ///    sheet.
3838    ///  * [`Scaffold::of`], for information about how to obtain the [`ScaffoldState`].
3839    ///  * The Material 2 spec at <https://m2.material.io/components/sheets-bottom>.
3840    ///  * The Material 3 spec at <https://m3.material.io/components/bottom-sheets/overview>.
3841    #[expect(
3842        clippy::too_many_arguments,
3843        reason = "Dart's named arguments, in Dart's order"
3844    )]
3845    pub fn show_bottom_sheet(
3846        self: Handle<Self>,
3847        app: &mut App,
3848        builder: WidgetBuilder,
3849        background_color: Option<Color>,
3850        elevation: Option<f64>,
3851        shape: Option<ShapeBorderRef>,
3852        clip_behavior: Option<Clip>,
3853        constraints: Option<BoxConstraints>,
3854        enable_drag: Option<bool>,
3855        show_drag_handle: Option<bool>,
3856        transition_animation_controller: Option<Ref<AnimationController>>,
3857        sheet_animation_style: Option<AnimationStyle>,
3858    ) -> Rc<PersistentBottomSheetController> {
3859        debug_assert!(
3860            self.widget(app).bottom_sheet.is_none(),
3861            "Scaffold.bottomSheet cannot be specified while a bottom sheet \
3862             displayed with showBottomSheet() is still visible.\n\
3863             Rebuild the Scaffold with a null bottomSheet before calling showBottomSheet()."
3864        );
3865        debug_assert!({
3866            let context = self.context(app);
3867            waft_widgets::debug_check_has_media_query(app, context)
3868        });
3869
3870        self.close_current_bottom_sheet(app);
3871        let should_dispose_animation_controller = transition_animation_controller.is_none();
3872        let controller = transition_animation_controller.unwrap_or_else(|| {
3873            BottomSheet::create_animation_controller(app, self, sheet_animation_style.as_ref())
3874        });
3875        controller.forward(app, None);
3876        let current_bottom_sheet = self.build_bottom_sheet(
3877            app,
3878            builder,
3879            false,
3880            controller,
3881            BottomSheetOptions {
3882                background_color,
3883                elevation,
3884                shape,
3885                clip_behavior,
3886                constraints,
3887                enable_drag,
3888                show_drag_handle,
3889                should_dispose_animation_controller,
3890            },
3891        );
3892        self.set_state(app, |state| {
3893            state.current_bottom_sheet = Some(current_bottom_sheet);
3894        });
3895        app.get(self)
3896            .current_bottom_sheet
3897            .clone()
3898            .expect("set above")
3899    }
3900
3901    // Floating Action Button API
3902
3903    fn floating_action_button_move_controller(
3904        self: Handle<Self>,
3905        app: &App,
3906    ) -> Handle<AnimationController> {
3907        app.get(self)
3908            .floating_action_button_move_controller
3909            .handle()
3910            .expect("made in init_state")
3911    }
3912
3913    fn floating_action_button_visibility_controller(
3914        self: Handle<Self>,
3915        app: &App,
3916    ) -> Handle<AnimationController> {
3917        app.get(self)
3918            .floating_action_button_visibility_controller
3919            .handle()
3920            .expect("made in init_state")
3921    }
3922
3923    fn floating_action_button_animator(
3924        self: Handle<Self>,
3925        app: &App,
3926    ) -> FloatingActionButtonAnimatorRef {
3927        Rc::clone(
3928            app.get(self)
3929                .floating_action_button_animator
3930                .as_ref()
3931                .expect("set in init_state"),
3932        )
3933    }
3934
3935    fn show_floating_action_button(self: Handle<Self>, app: &mut App) -> TickerFuture {
3936        self.floating_action_button_visibility_controller(app)
3937            .forward(app, None)
3938    }
3939
3940    // Moves the Floating Action Button to the new Floating Action Button Location.
3941    fn move_floating_action_button(
3942        self: Handle<Self>,
3943        app: &mut App,
3944        new_location: FloatingActionButtonLocationRef,
3945    ) {
3946        let mut previous_location = app.get(self).floating_action_button_location.clone();
3947        let mut restart_animation_from = 0.0;
3948        let move_controller = self.floating_action_button_move_controller(app);
3949        // If the Floating Action Button is moving right now, we need to start from a snapshot
3950        // of the current transition.
3951        if move_controller.is_animating(app) {
3952            let animator = self.floating_action_button_animator(app);
3953            let this = app.get(self);
3954            previous_location = Some(Rc::new(TransitionSnapshotFabLocation {
3955                begin: Rc::clone(
3956                    this.previous_floating_action_button_location
3957                        .as_ref()
3958                        .expect("set in init_state"),
3959                ),
3960                end: Rc::clone(
3961                    this.floating_action_button_location
3962                        .as_ref()
3963                        .expect("set in init_state"),
3964                ),
3965                animator: Rc::clone(&animator),
3966                progress: move_controller.value(app),
3967            }));
3968            restart_animation_from = animator.get_animation_restart(move_controller.value(app));
3969        }
3970
3971        self.set_state(app, move |state| {
3972            state.previous_floating_action_button_location = previous_location;
3973            state.floating_action_button_location = Some(new_location);
3974        });
3975
3976        // Animate the motion even when the fab is null so that if the exit animation is
3977        // running, the old fab will start the motion transition while it exits instead of
3978        // jumping to the new position.
3979        move_controller.forward(app, Some(restart_animation_from));
3980    }
3981
3982    // iOS FEATURES - status bar tap, back gesture
3983
3984    // On iOS, if `primary` is true, tapping the status bar scrolls the app's primary
3985    // scrollable to the top. We implement this by looking up the primary scroll controller
3986    // and scrolling it to the top when tapped.
3987    /// Dart's `WidgetsBindingObserver.handleStatusBarTap` override.
3988    pub fn handle_status_bar_tap(self: Handle<Self>, app: &mut App) {
3989        debug_assert!(self.widget(app).primary);
3990        let context = self.context(app);
3991        let primary_scroll_controller = PrimaryScrollController::maybe_of(app, context);
3992        let status_bar_key = app.get(self).status_bar_key.clone();
3993        if let Some(primary_scroll_controller) = primary_scroll_controller
3994            && primary_scroll_controller.has_clients(app)
3995            // TODO(LongCatIsLooong): the iOS embedder used to send status bar tap
3996            // evets as fake touches at Offset.zero, such that at most one Scaffold
3997            // (usually the foreground primary Scaffold) can handle the status bar
3998            // tap event, thanks to hit-testing and gesture disambiguation.
3999            // To keep that behavior, this widget performs an additional hit-test here
4000            // to make sure the status bar tap is only handled if the scaffold is
4001            // hit-testable (thus in the foreground)
4002            // Switch to a better solution when available:
4003            // https://github.com/flutter/flutter/issues/182403
4004            && HitTestableAtOrigin::hit_testable_at_origin(app, &status_bar_key)
4005        {
4006            primary_scroll_controller.animate_to(
4007                app,
4008                0.0,
4009                Duration::from_millis(1000),
4010                Curves::ease_out_circ(),
4011            );
4012        }
4013    }
4014
4015    // INTERNALS
4016
4017    fn geometry_notifier(self: Handle<Self>, app: &App) -> Ref<ScaffoldGeometryNotifier> {
4018        app.get(self)
4019            .geometry_notifier
4020            .clone()
4021            .expect("made in init_state")
4022    }
4023
4024    fn resize_to_avoid_bottom_inset(self: Handle<Self>, app: &App) -> bool {
4025        self.widget(app)
4026            .resize_to_avoid_bottom_inset
4027            .unwrap_or(true)
4028    }
4029
4030    fn observer(self: Handle<Self>, app: &mut App) -> WidgetsBindingObserverRef {
4031        if let Some(observer) = app.get(self).observer.clone() {
4032            return observer;
4033        }
4034        let observer: WidgetsBindingObserverRef = Rc::new(self);
4035        app.get_mut(self).observer = Some(observer.clone());
4036        observer
4037    }
4038
4039    #[expect(
4040        clippy::too_many_arguments,
4041        reason = "Dart's named arguments, in Dart's order"
4042    )]
4043    fn add_if_non_null(
4044        self: Handle<Self>,
4045        app: &mut App,
4046        children: &mut Vec<WidgetRef>,
4047        child: Option<WidgetRef>,
4048        child_id: ScaffoldSlot,
4049        remove_left_padding: bool,
4050        remove_top_padding: bool,
4051        remove_right_padding: bool,
4052        remove_bottom_padding: bool,
4053        remove_bottom_inset: bool,
4054        maintain_bottom_view_padding: bool,
4055    ) {
4056        let context = self.context(app);
4057        let mut data = MediaQuery::of(app, context).remove_padding(
4058            remove_left_padding,
4059            remove_top_padding,
4060            remove_right_padding,
4061            remove_bottom_padding,
4062        );
4063        if remove_bottom_inset {
4064            data = data.remove_view_insets(false, false, false, true);
4065        }
4066
4067        if maintain_bottom_view_padding && data.view_insets.bottom != 0.0 {
4068            let padding = data
4069                .padding
4070                .copy_with(None, None, None, Some(data.view_padding.bottom));
4071            data = data.copy_with().padding(padding);
4072        }
4073
4074        if let Some(child) = child {
4075            children.push(
4076                LayoutId::new(child_id.id(), MediaQuery::new(data, child).into_widget())
4077                    .into_widget(),
4078            );
4079        }
4080    }
4081
4082    fn build_end_drawer(
4083        self: Handle<Self>,
4084        app: &mut App,
4085        children: &mut Vec<WidgetRef>,
4086        text_direction: TextDirection,
4087    ) {
4088        if let Some(end_drawer) = self.widget(app).end_drawer.clone() {
4089            debug_assert!(self.has_end_drawer(app));
4090            let widget = self.widget(app);
4091            let mut controller = DrawerController::new(end_drawer, DrawerAlignment::End)
4092                .key(app.get(self).end_drawer_key.clone())
4093                .drawer_callback(Rc::new(move |app: &mut App, is_opened: bool| {
4094                    self.end_drawer_opened_callback(app, is_opened)
4095                }))
4096                .drag_start_behavior(widget.drawer_drag_start_behavior)
4097                .enable_open_drag_gesture(widget.end_drawer_enable_open_drag_gesture)
4098                .drawer_barrier_dismissible(widget.drawer_barrier_dismissible);
4099            if let Some(scrim_color) = widget.drawer_scrim_color {
4100                controller = controller.scrim_color(scrim_color);
4101            }
4102            if let Some(edge_drag_width) = widget.drawer_edge_drag_width {
4103                controller = controller.edge_drag_width(edge_drag_width);
4104            }
4105            let controller = controller.is_drawer_open(self.is_end_drawer_open(app));
4106            self.add_if_non_null(
4107                app,
4108                children,
4109                Some(controller.into_widget()),
4110                ScaffoldSlot::EndDrawer,
4111                // remove the side padding from the side we're not touching
4112                text_direction == TextDirection::Ltr,
4113                false,
4114                text_direction == TextDirection::Rtl,
4115                false,
4116                false,
4117                false,
4118            );
4119        }
4120    }
4121
4122    fn build_drawer(
4123        self: Handle<Self>,
4124        app: &mut App,
4125        children: &mut Vec<WidgetRef>,
4126        text_direction: TextDirection,
4127    ) {
4128        if let Some(drawer) = self.widget(app).drawer.clone() {
4129            debug_assert!(self.has_drawer(app));
4130            let widget = self.widget(app);
4131            let mut controller = DrawerController::new(drawer, DrawerAlignment::Start)
4132                .key(app.get(self).drawer_key.clone())
4133                .drawer_callback(Rc::new(move |app: &mut App, is_opened: bool| {
4134                    self.drawer_opened_callback(app, is_opened)
4135                }))
4136                .drag_start_behavior(widget.drawer_drag_start_behavior)
4137                .enable_open_drag_gesture(widget.drawer_enable_open_drag_gesture)
4138                .drawer_barrier_dismissible(widget.drawer_barrier_dismissible);
4139            if let Some(scrim_color) = widget.drawer_scrim_color {
4140                controller = controller.scrim_color(scrim_color);
4141            }
4142            if let Some(edge_drag_width) = widget.drawer_edge_drag_width {
4143                controller = controller.edge_drag_width(edge_drag_width);
4144            }
4145            let controller = controller.is_drawer_open(self.is_drawer_open(app));
4146            self.add_if_non_null(
4147                app,
4148                children,
4149                Some(controller.into_widget()),
4150                ScaffoldSlot::Drawer,
4151                // remove the side padding from the side we're not touching
4152                text_direction == TextDirection::Rtl,
4153                false,
4154                text_direction == TextDirection::Ltr,
4155                false,
4156                false,
4157                false,
4158            );
4159        }
4160    }
4161
4162    fn bottom_sheet_scrim_animation_controller(
4163        self: Handle<Self>,
4164        app: &App,
4165    ) -> Handle<AnimationController> {
4166        app.get(self)
4167            .bottom_sheet_scrim_animation_controller
4168            .handle()
4169            .expect("made in init_state")
4170    }
4171
4172    /// Whether to show a [`ModalBarrier`] over the body of the scaffold.
4173    ///
4174    /// The `value` parameter must not be null.
4175    pub fn show_body_scrim(self: Handle<Self>, app: &mut App, value: bool, animation_value: f64) {
4176        if app.get(self).show_body_scrim != value {
4177            self.set_state(app, |state| {
4178                state.show_body_scrim = value;
4179            });
4180        }
4181        let controller = self.bottom_sheet_scrim_animation_controller(app);
4182        if controller.value(app) != animation_value {
4183            controller.set_value(app, animation_value);
4184        }
4185    }
4186}
4187
4188/// The optional arguments [`ScaffoldState::build_bottom_sheet`] passes on to the sheet.
4189struct BottomSheetOptions {
4190    background_color: Option<Color>,
4191    elevation: Option<f64>,
4192    shape: Option<ShapeBorderRef>,
4193    clip_behavior: Option<Clip>,
4194    constraints: Option<BoxConstraints>,
4195    enable_drag: Option<bool>,
4196    show_drag_handle: Option<bool>,
4197    /// Dart's `shouldDisposeAnimationController = true`.
4198    should_dispose_animation_controller: bool,
4199}
4200
4201impl Default for BottomSheetOptions {
4202    fn default() -> BottomSheetOptions {
4203        BottomSheetOptions {
4204            background_color: None,
4205            elevation: None,
4206            shape: None,
4207            clip_behavior: None,
4208            constraints: None,
4209            enable_drag: None,
4210            show_drag_handle: None,
4211            should_dispose_animation_controller: true,
4212        }
4213    }
4214}
4215
4216impl TickerProviderStateMixin for ScaffoldState {
4217    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
4218        &app.get(self).ticker_provider
4219    }
4220
4221    fn ticker_provider_data_mut(
4222        self: Handle<Self>,
4223        app: &mut App,
4224    ) -> &mut TickerProviderStateMixinData {
4225        &mut app.get_mut(self).ticker_provider
4226    }
4227}
4228
4229/// Dart's `vsync: this`.
4230impl TickerProviderObject for ScaffoldState {
4231    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
4232        TickerProviderStateMixin::create_ticker(self, app, on_tick)
4233    }
4234}
4235
4236impl RestorationMixin for ScaffoldState {
4237    waft_widgets::restoration_mixin_accessors!();
4238
4239    fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
4240        self.widget(app).restoration_id.as_deref()
4241    }
4242
4243    fn restore_state(
4244        self: Handle<Self>,
4245        app: &mut App,
4246        _old_bucket: Option<Handle<RestorationBucket>>,
4247        _initial_restore: bool,
4248    ) {
4249        let drawer_opened = self.drawer_opened(app);
4250        self.register_for_restoration(app, drawer_opened.as_property(), "drawer_open");
4251        let end_drawer_opened = self.end_drawer_opened(app);
4252        self.register_for_restoration(app, end_drawer_opened.as_property(), "end_drawer_open");
4253    }
4254}
4255
4256impl WidgetsBindingObserverObject for ScaffoldState {}
4257
4258impl State for ScaffoldState {
4259    type Widget = Scaffold;
4260    waft_widgets::state_accessors!();
4261
4262    fn init_state(self: Handle<Self>, app: &mut App) {
4263        let drawer_opened = RestorableBool::new(app, false);
4264        let end_drawer_opened = RestorableBool::new(app, false);
4265        let context = self.context(app);
4266        let geometry_notifier =
4267            ScaffoldGeometryNotifier::new(app, ScaffoldGeometry::new(), context);
4268        let floating_action_button_location = self
4269            .widget(app)
4270            .floating_action_button_location
4271            .clone()
4272            .unwrap_or_else(default_floating_action_button_location);
4273        let floating_action_button_animator = self
4274            .widget(app)
4275            .floating_action_button_animator
4276            .clone()
4277            .unwrap_or_else(default_floating_action_button_animator);
4278        let floating_action_button_move_controller = AnimationController::new(
4279            app,
4280            Some(1.0),
4281            Some(K_FLOATING_ACTION_BUTTON_SEGUE * 2),
4282            None,
4283            0.0,
4284            1.0,
4285            waft_animation::AnimationBehavior::Normal,
4286            self,
4287        );
4288
4289        let floating_action_button_visibility_controller = AnimationController::new(
4290            app,
4291            None,
4292            Some(K_FLOATING_ACTION_BUTTON_SEGUE),
4293            None,
4294            0.0,
4295            1.0,
4296            waft_animation::AnimationBehavior::Normal,
4297            self,
4298        );
4299
4300        let bottom_sheet_scrim_animation_controller = AnimationController::new(
4301            app,
4302            None,
4303            None,
4304            None,
4305            0.0,
4306            1.0,
4307            waft_animation::AnimationBehavior::Normal,
4308            self,
4309        );
4310        let this = app.get_mut(self);
4311        this.drawer_opened = Some(drawer_opened);
4312        this.end_drawer_opened = Some(end_drawer_opened);
4313        this.geometry_notifier = Some(geometry_notifier);
4314        this.previous_floating_action_button_location =
4315            Some(Rc::clone(&floating_action_button_location));
4316        this.floating_action_button_location = Some(floating_action_button_location);
4317        this.floating_action_button_animator = Some(floating_action_button_animator);
4318        this.floating_action_button_move_controller = Some(floating_action_button_move_controller);
4319        this.floating_action_button_visibility_controller =
4320            Some(floating_action_button_visibility_controller);
4321        this.bottom_sheet_scrim_animation_controller =
4322            Some(bottom_sheet_scrim_animation_controller);
4323        if self.widget(app).primary {
4324            let observer = self.observer(app);
4325            WidgetsBinding::instance(app).add_observer(app, observer);
4326        }
4327    }
4328
4329    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Scaffold) {
4330        self.did_update_restoration_id(app);
4331        // Update the Floating Action Button Animator, and then schedule the Floating Action
4332        // Button for repositioning.
4333        if !option_rc_ptr_eq(
4334            &self.widget(app).floating_action_button_animator,
4335            &old_widget.floating_action_button_animator,
4336        ) {
4337            let animator = self
4338                .widget(app)
4339                .floating_action_button_animator
4340                .clone()
4341                .unwrap_or_else(default_floating_action_button_animator);
4342            app.get_mut(self).floating_action_button_animator = Some(animator);
4343        }
4344        if !option_rc_ptr_eq(
4345            &self.widget(app).floating_action_button_location,
4346            &old_widget.floating_action_button_location,
4347        ) {
4348            let location = self
4349                .widget(app)
4350                .floating_action_button_location
4351                .clone()
4352                .unwrap_or_else(default_floating_action_button_location);
4353            self.move_floating_action_button(app, location);
4354        }
4355        if !option_rc_ptr_eq(&self.widget(app).bottom_sheet, &old_widget.bottom_sheet) {
4356            debug_assert!(
4357                !(self.widget(app).bottom_sheet.is_some()
4358                    && app
4359                        .get(self)
4360                        .current_bottom_sheet
4361                        .as_ref()
4362                        .is_some_and(|sheet| sheet.is_local_history_entry)),
4363                "Scaffold.bottomSheet cannot be specified while a bottom sheet displayed \
4364                 with showBottomSheet() is still visible.\n\
4365                 Use the PersistentBottomSheetController \
4366                 returned by showBottomSheet() to close the old bottom sheet before creating \
4367                 a Scaffold with a (non null) bottomSheet."
4368            );
4369            if self.widget(app).bottom_sheet.is_none() {
4370                self.close_current_bottom_sheet(app);
4371            } else if self.widget(app).bottom_sheet.is_some() && old_widget.bottom_sheet.is_none() {
4372                self.maybe_build_persistent_bottom_sheet(app);
4373            } else {
4374                self.update_persistent_bottom_sheet(app);
4375            }
4376        }
4377        match (old_widget.primary, self.widget(app).primary) {
4378            (true, false) => {
4379                let observer = self.observer(app);
4380                WidgetsBinding::instance(app).remove_observer(app, &observer);
4381            }
4382            (false, true) => {
4383                let observer = self.observer(app);
4384                WidgetsBinding::instance(app).add_observer(app, observer);
4385            }
4386            (true, true) | (false, false) => {}
4387        }
4388    }
4389
4390    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
4391        // Using maybeOf is valid here since both the Scaffold and ScaffoldMessenger
4392        // are currently available for managing SnackBars.
4393        let context = self.context(app);
4394        let current_scaffold_messenger = ScaffoldMessenger::maybe_of(app, context);
4395        // If our ScaffoldMessenger has changed, unregister with the old one first.
4396        if let Some(scaffold_messenger) = app.get(self).scaffold_messenger
4397            && current_scaffold_messenger != Some(scaffold_messenger)
4398        {
4399            scaffold_messenger.unregister(app, self);
4400        }
4401        // Register with the current ScaffoldMessenger, if there is one.
4402        app.get_mut(self).scaffold_messenger = current_scaffold_messenger;
4403        if let Some(scaffold_messenger) = current_scaffold_messenger {
4404            scaffold_messenger.register(app, self);
4405        }
4406
4407        self.maybe_build_persistent_bottom_sheet(app);
4408        self.did_change_dependencies_restoration(app);
4409    }
4410
4411    fn deactivate(self: Handle<Self>, app: &mut App) {
4412        let observer = self.observer(app);
4413        WidgetsBinding::instance(app).remove_observer(app, &observer);
4414    }
4415
4416    fn activate(self: Handle<Self>, app: &mut App) {
4417        TickerProviderStateMixin::activate(self, app);
4418        if self.widget(app).primary {
4419            let observer = self.observer(app);
4420            WidgetsBinding::instance(app).add_observer(app, observer);
4421        }
4422    }
4423
4424    fn dispose(self: Handle<Self>, app: &mut App) {
4425        self.geometry_notifier(app).dispose(app);
4426        self.floating_action_button_move_controller(app)
4427            .dispose(app);
4428        self.floating_action_button_visibility_controller(app)
4429            .dispose(app);
4430        if let Some(scaffold_messenger) = app.get(self).scaffold_messenger {
4431            scaffold_messenger.unregister(app, self);
4432        }
4433        RestorableProperty::dispose(self.drawer_opened(app), app);
4434        RestorableProperty::dispose(self.end_drawer_opened(app), app);
4435        self.bottom_sheet_scrim_animation_controller(app)
4436            .dispose(app);
4437        self.dispose_restoration(app);
4438        TickerProviderStateMixin::dispose(self, app);
4439    }
4440
4441    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
4442        debug_assert!(waft_widgets::debug_check_has_media_query(app, context));
4443        debug_assert!(waft_widgets::debug_check_has_directionality(
4444            app, context, None, None, None
4445        ));
4446        let theme_data = Theme::of(app, context);
4447        let text_direction = waft_widgets::Directionality::of(app, context);
4448
4449        let mut children = Vec::new();
4450        let body = self.widget(app).body.clone().map(|body| {
4451            BodyBuilder::new(
4452                self.widget(app).extend_body,
4453                self.widget(app).extend_body_behind_app_bar,
4454                KeyedSubtree::new(body)
4455                    .key(app.get(self).body_key.clone().into())
4456                    .into_widget(),
4457            )
4458            .into_widget()
4459        });
4460        let remove_bottom_padding = self.widget(app).bottom_navigation_bar.is_some()
4461            || self.widget(app).persistent_footer_buttons.is_some();
4462        let resize_to_avoid_bottom_inset = self.resize_to_avoid_bottom_inset(app);
4463        let has_app_bar = self.widget(app).app_bar.is_some();
4464        self.add_if_non_null(
4465            app,
4466            &mut children,
4467            body,
4468            ScaffoldSlot::Body,
4469            false,
4470            has_app_bar,
4471            false,
4472            remove_bottom_padding,
4473            resize_to_avoid_bottom_inset,
4474            false,
4475        );
4476        if app.get(self).show_body_scrim {
4477            let scrim_builder = Rc::clone(&self.widget(app).bottom_sheet_scrim_builder);
4478            let scrim_animation: AnimationRef<f64> = app
4479                .get(self)
4480                .bottom_sheet_scrim_animation_controller
4481                .as_ref()
4482                .expect("set in init_state")
4483                .erase();
4484            let scrim = scrim_builder(app, context, scrim_animation);
4485            self.add_if_non_null(
4486                app,
4487                &mut children,
4488                scrim,
4489                ScaffoldSlot::BodyScrim,
4490                true,
4491                true,
4492                true,
4493                true,
4494                false,
4495                false,
4496            );
4497        }
4498
4499        if let Some(app_bar) = self.widget(app).app_bar.clone() {
4500            let top_padding = if self.widget(app).primary {
4501                MediaQuery::padding_of(app, context).top
4502            } else {
4503                0.0
4504            };
4505            let app_bar_max_height =
4506                AppBar::preferred_height_for(app, context, &app_bar.preferred_size()) + top_padding;
4507            app.get_mut(self).app_bar_max_height = Some(app_bar_max_height);
4508            debug_assert!(app_bar_max_height >= 0.0 && app_bar_max_height.is_finite());
4509            self.add_if_non_null(
4510                app,
4511                &mut children,
4512                Some(
4513                    ConstrainedBox::new(BoxConstraints::new().max_height(app_bar_max_height))
4514                        .child(
4515                            FlexibleSpaceBar::create_settings(app_bar_max_height, app_bar).build(),
4516                        )
4517                        .into_widget(),
4518                ),
4519                ScaffoldSlot::AppBar,
4520                false,
4521                false,
4522                false,
4523                true,
4524                false,
4525                false,
4526            );
4527        }
4528
4529        let mut is_snack_bar_floating = false;
4530        let mut snack_bar_width = None;
4531
4532        if app.get(self).current_bottom_sheet.is_some()
4533            || !app.get(self).dismissed_bottom_sheets.is_empty()
4534        {
4535            let this = app.get(self);
4536            let mut sheets = this.dismissed_bottom_sheets.to_vec();
4537            if let Some(current_bottom_sheet) = &this.current_bottom_sheet {
4538                sheets.push(current_bottom_sheet.feature.widget.clone());
4539            }
4540            let stack = LayoutBuilder::new(move |_app, _context, constraints| {
4541                BottomSheetKeyboardInset {
4542                    inset: constraints
4543                        .extension::<BottomSheetBoxConstraints>()
4544                        .expect("the scaffold lays out its bottom sheet with _BottomSheetBoxConstraints")
4545                        .keyboard_inset,
4546                    child: Stack::new()
4547                        .alignment(AlignmentGeometry::BOTTOM_CENTER)
4548                        .children(sheets.clone())
4549                        .into_widget(),
4550                }
4551                .into_widget()
4552            })
4553            .into_widget();
4554            self.add_if_non_null(
4555                app,
4556                &mut children,
4557                Some(stack),
4558                ScaffoldSlot::BottomSheet,
4559                false,
4560                true,
4561                false,
4562                resize_to_avoid_bottom_inset,
4563                false,
4564                false,
4565            );
4566        }
4567
4568        // SnackBar set by ScaffoldMessenger
4569        if let Some(messenger_snack_bar) = app.get(self).messenger_snack_bar.clone() {
4570            let snack_bar_theme = SnackBarTheme::of(app, context);
4571            let snack_bar_behavior = messenger_snack_bar
4572                .widget()
4573                .behavior
4574                .or(snack_bar_theme.behavior)
4575                .unwrap_or(SnackBarBehavior::Fixed);
4576            is_snack_bar_floating = snack_bar_behavior == SnackBarBehavior::Floating;
4577            snack_bar_width = messenger_snack_bar.widget().width.or(snack_bar_theme.width);
4578
4579            self.add_if_non_null(
4580                app,
4581                &mut children,
4582                Some(messenger_snack_bar.widget.clone()),
4583                ScaffoldSlot::SnackBar,
4584                false,
4585                true,
4586                false,
4587                remove_bottom_padding,
4588                false,
4589                !resize_to_avoid_bottom_inset,
4590            );
4591        }
4592
4593        let mut extend_body_behind_material_banner = false;
4594        // MaterialBanner set by ScaffoldMessenger
4595        if let Some(messenger_material_banner) = app.get(self).messenger_material_banner.clone() {
4596            let banner_theme = MaterialBannerTheme::of(app, context);
4597            let elevation = messenger_material_banner
4598                .widget()
4599                .elevation
4600                .or(banner_theme.elevation)
4601                .unwrap_or(0.0);
4602            extend_body_behind_material_banner = elevation != 0.0;
4603
4604            self.add_if_non_null(
4605                app,
4606                &mut children,
4607                Some(messenger_material_banner.widget.clone()),
4608                ScaffoldSlot::MaterialBanner,
4609                false,
4610                has_app_bar,
4611                false,
4612                true,
4613                false,
4614                !resize_to_avoid_bottom_inset,
4615            );
4616        }
4617
4618        if let Some(persistent_footer_buttons) = self.widget(app).persistent_footer_buttons.clone()
4619        {
4620            let decoration = match self.widget(app).persistent_footer_decoration.clone() {
4621                Some(decoration) => decoration,
4622                None => BoxDecoration::new().border(Border {
4623                    top: Divider::create_border_side(app, Some(context), None, Some(1.0)),
4624                    ..Border::default()
4625                }),
4626            };
4627            let footer = Container::new()
4628                .decoration(decoration)
4629                .child(
4630                    SafeArea::new(
4631                        IntrinsicHeight::new().child(
4632                            Padding::new(EdgeInsetsGeometry::all(8.0)).child(
4633                                Align::new()
4634                                    .alignment(self.widget(app).persistent_footer_alignment.into())
4635                                    .child(
4636                                        OverflowBar::new()
4637                                            .spacing(8.0)
4638                                            .overflow_alignment(OverflowBarAlignment::End)
4639                                            .children(persistent_footer_buttons),
4640                                    ),
4641                            ),
4642                        ),
4643                    )
4644                    .top(false),
4645                )
4646                .into_widget();
4647            let remove_bottom_padding = self.widget(app).bottom_navigation_bar.is_some();
4648            self.add_if_non_null(
4649                app,
4650                &mut children,
4651                Some(footer),
4652                ScaffoldSlot::PersistentFooter,
4653                false,
4654                true,
4655                false,
4656                remove_bottom_padding,
4657                false,
4658                !resize_to_avoid_bottom_inset,
4659            );
4660        }
4661
4662        if let Some(bottom_navigation_bar) = self.widget(app).bottom_navigation_bar.clone() {
4663            self.add_if_non_null(
4664                app,
4665                &mut children,
4666                Some(bottom_navigation_bar),
4667                ScaffoldSlot::BottomNavigationBar,
4668                false,
4669                true,
4670                false,
4671                false,
4672                false,
4673                !resize_to_avoid_bottom_inset,
4674            );
4675        }
4676
4677        let fab_transition = FloatingActionButtonTransition {
4678            child: self.widget(app).floating_action_button.clone(),
4679            fab_move_animation: app
4680                .get(self)
4681                .floating_action_button_move_controller
4682                .as_ref()
4683                .expect("set in init_state")
4684                .erase(),
4685            fab_motion_animator: self.floating_action_button_animator(app),
4686            geometry_notifier: self.geometry_notifier(app),
4687            current_controller: app
4688                .get(self)
4689                .floating_action_button_visibility_controller
4690                .clone()
4691                .expect("set in init_state"),
4692        };
4693        self.add_if_non_null(
4694            app,
4695            &mut children,
4696            Some(fab_transition.into_widget()),
4697            ScaffoldSlot::FloatingActionButton,
4698            true,
4699            true,
4700            true,
4701            true,
4702            false,
4703            false,
4704        );
4705
4706        let status_bar = match theme_data.platform {
4707            TargetPlatform::IOS | TargetPlatform::MacOS => self.widget(app).primary.then(|| {
4708                HitTestableAtOrigin::new(app.get(self).status_bar_key.clone()).into_widget()
4709            }),
4710            TargetPlatform::Android
4711            | TargetPlatform::Fuchsia
4712            | TargetPlatform::Linux
4713            | TargetPlatform::Windows => None,
4714        };
4715
4716        self.add_if_non_null(
4717            app,
4718            &mut children,
4719            status_bar,
4720            ScaffoldSlot::StatusBar,
4721            false,
4722            true,
4723            false,
4724            true,
4725            false,
4726            false,
4727        );
4728
4729        if self.is_end_drawer_open(app) {
4730            self.build_drawer(app, &mut children, text_direction);
4731            self.build_end_drawer(app, &mut children, text_direction);
4732        } else {
4733            self.build_end_drawer(app, &mut children, text_direction);
4734            self.build_drawer(app, &mut children, text_direction);
4735        }
4736
4737        // The minimum insets for contents of the Scaffold to keep visible.
4738        let view_insets_bottom = MediaQuery::view_insets_of(app, context).bottom;
4739        let min_insets = MediaQuery::padding_of(app, context).copy_with(
4740            None,
4741            None,
4742            None,
4743            Some(if resize_to_avoid_bottom_inset {
4744                view_insets_bottom
4745            } else {
4746                0.0
4747            }),
4748        );
4749
4750        // The minimum viewPadding for interactive elements positioned by the
4751        // Scaffold to keep within safe interactive areas.
4752        let min_view_padding = MediaQuery::view_padding_of(app, context).copy_with(
4753            None,
4754            None,
4755            None,
4756            (resize_to_avoid_bottom_inset && view_insets_bottom != 0.0).then_some(0.0),
4757        );
4758
4759        let move_animation: AnimationRef<f64> = app
4760            .get(self)
4761            .floating_action_button_move_controller
4762            .as_ref()
4763            .expect("set in init_state")
4764            .erase();
4765        let extend_body = self.widget(app).extend_body;
4766        let extend_body_behind_app_bar = self.widget(app).extend_body_behind_app_bar;
4767        let this = app.get(self);
4768        let delegate = Rc::new(ScaffoldLayout {
4769            extend_body,
4770            extend_body_behind_app_bar,
4771            min_insets,
4772            min_view_padding,
4773            current_floating_action_button_location: Rc::clone(
4774                this.floating_action_button_location
4775                    .as_ref()
4776                    .expect("set in init_state"),
4777            ),
4778            relayout: Rc::new(move_animation.clone()),
4779            floating_action_button_move_animation: move_animation,
4780            floating_action_button_motion_animator: Rc::clone(
4781                this.floating_action_button_animator
4782                    .as_ref()
4783                    .expect("set in init_state"),
4784            ),
4785            geometry_notifier: this.geometry_notifier.clone().expect("made in init_state"),
4786            previous_floating_action_button_location: Rc::clone(
4787                this.previous_floating_action_button_location
4788                    .as_ref()
4789                    .expect("set in init_state"),
4790            ),
4791            text_direction,
4792            is_snack_bar_floating,
4793            extend_body_behind_material_banner,
4794            snack_bar_width,
4795        });
4796
4797        ScaffoldScope {
4798            has_drawer: self.has_drawer(app),
4799            has_end_drawer: self.has_end_drawer(app),
4800            is_drawer_open: self.is_drawer_open(app),
4801            is_end_drawer_open: self.is_end_drawer_open(app),
4802            geometry_notifier: self.geometry_notifier(app),
4803            child: ScrollNotificationObserver::new(
4804                Material::new()
4805                    .color(
4806                        self.widget(app)
4807                            .background_color
4808                            .unwrap_or(theme_data.scaffold_background_color),
4809                    )
4810                    .child(Builder::new(move |app, context| {
4811                        let dismiss_drawer_action = DismissDrawerAction::new(app, context);
4812                        let mut actions = HashMap::new();
4813                        actions.insert(
4814                            <DismissDrawerAction as Action>::intent_type(),
4815                            dismiss_drawer_action.erase(),
4816                        );
4817                        Actions::new(
4818                            actions,
4819                            CustomMultiChildLayout::new(delegate.clone())
4820                                .children(children.clone()),
4821                        )
4822                        .into_widget()
4823                    })),
4824            )
4825            .into_widget(),
4826        }
4827        .into_widget()
4828    }
4829}
4830
4831/// Whether a panic is the framework's `setState` during build: Dart's
4832/// `exception is FlutterError` whose summary is 'setState() or markNeedsBuild() called during
4833/// build.'.
4834fn is_set_state_during_build(exception: &(dyn Any + Send)) -> bool {
4835    let message = exception
4836        .downcast_ref::<&str>()
4837        .copied()
4838        .or_else(|| exception.downcast_ref::<String>().map(String::as_str));
4839    message.is_some_and(|message| {
4840        message.starts_with("setState() or markNeedsBuild() called during build.")
4841    })
4842}
4843
4844fn option_rc_ptr_eq<T: ?Sized>(a: &Option<Rc<T>>, b: &Option<Rc<T>>) -> bool {
4845    match (a, b) {
4846        (None, None) => true,
4847        (Some(a), Some(b)) => Rc::ptr_eq(a, b),
4848        _ => false,
4849    }
4850}
4851
4852/// Dart's `_DismissDrawerAction`.
4853struct DismissDrawerAction {
4854    action: ActionData,
4855    /// The context of the scaffold's `Builder`, which sets it on every build; until the first,
4856    /// the scaffold's own, which nothing can invoke the action from.
4857    context: BuildContext,
4858}
4859
4860impl DismissDrawerAction {
4861    fn new(app: &mut App, context: BuildContext) -> Ref<DismissDrawerAction> {
4862        app.create(DismissDrawerAction {
4863            action: ActionData::new(),
4864            context,
4865        })
4866    }
4867}
4868
4869impl Action for DismissDrawerAction {
4870    type Intent = DismissIntent;
4871
4872    waft_widgets::action_accessors!();
4873
4874    fn is_enabled(self: Handle<Self>, app: &mut App, _intent: &DismissIntent) -> bool {
4875        let context = app.get(self).context;
4876        let scaffold = Scaffold::of(app, context);
4877        (scaffold.is_drawer_open(app) || scaffold.is_end_drawer_open(app))
4878            && scaffold.is_drawer_barrier_dismissible(app)
4879    }
4880
4881    fn invoke(self: Handle<Self>, app: &mut App, intent: &DismissIntent) -> Option<Rc<dyn Any>> {
4882        let context = app.get(self).context;
4883        let scaffold = Scaffold::of(app, context);
4884        if Action::is_enabled(self, app, intent) {
4885            scaffold.close_drawer(app);
4886            scaffold.close_end_drawer(app);
4887        }
4888        None
4889    }
4890}
4891
4892impl DismissAction for DismissDrawerAction {}
4893
4894/// An interface for controlling a feature of a [`Scaffold`].
4895///
4896/// Commonly obtained from [`ScaffoldMessengerState::show_snack_bar`] or
4897/// [`ScaffoldState::show_bottom_sheet`].
4898///
4899/// Dart compares controllers by identity; here they are shared as `Rc`s and compared with
4900/// `Rc::ptr_eq`.
4901pub struct ScaffoldFeatureController<T, U> {
4902    /// Dart's `_widget`, as the tree node the scaffold places.
4903    widget: WidgetRef,
4904    completer: Completer<U>,
4905
4906    /// Remove the feature (e.g., bottom sheet, snack bar, or material banner) from the
4907    /// scaffold.
4908    pub close: VoidCallback,
4909
4910    /// Mark the feature (e.g., bottom sheet or snack bar) as needing to rebuild.
4911    pub set_state: Option<StateSetter>,
4912
4913    _widget_type: PhantomData<T>,
4914}
4915
4916impl<T: 'static, U: Clone + 'static> ScaffoldFeatureController<T, U> {
4917    #[cfg_attr(debug_assertions, track_caller)]
4918    fn new<K>(
4919        widget: impl IntoWidget<K>,
4920        completer: Completer<U>,
4921        close: VoidCallback,
4922        set_state: Option<StateSetter>,
4923    ) -> ScaffoldFeatureController<T, U> {
4924        ScaffoldFeatureController {
4925            widget: widget.into_widget(),
4926            completer,
4927            close,
4928            set_state,
4929            _widget_type: PhantomData,
4930        }
4931    }
4932
4933    /// Dart's `_widget`.
4934    fn widget(&self) -> &T {
4935        downcast_widget::<T>(&*self.widget).expect("the controller's widget keeps its type")
4936    }
4937
4938    /// Completes when the feature controlled by this object is no longer visible.
4939    pub fn closed(&self) -> CompleterFuture<U> {
4940        self.completer.future()
4941    }
4942}
4943
4944impl<T, U> Debug for ScaffoldFeatureController<T, U> {
4945    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4946        f.debug_struct("ScaffoldFeatureController")
4947            .field("widget", &self.widget)
4948            .finish_non_exhaustive()
4949    }
4950}
4951
4952/// Dart's `_StandardBottomSheet`.
4953struct StandardBottomSheet {
4954    key: KeyRef,
4955    // we control it, but it must be disposed by whoever created it.
4956    animation_controller: Ref<AnimationController>,
4957    enable_drag: bool,
4958    show_drag_handle: Option<bool>,
4959    on_closing: Option<VoidCallback>,
4960    on_dismissed: Option<VoidCallback>,
4961    on_dispose: Option<VoidCallback>,
4962    builder: WidgetBuilder,
4963    is_persistent: bool,
4964    background_color: Option<Color>,
4965    elevation: Option<f64>,
4966    shape: Option<ShapeBorderRef>,
4967    clip_behavior: Option<Clip>,
4968    constraints: Option<BoxConstraints>,
4969}
4970
4971impl Debug for StandardBottomSheet {
4972    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4973        f.debug_struct("_StandardBottomSheet")
4974            .field("enableDrag", &self.enable_drag)
4975            .field("isPersistent", &self.is_persistent)
4976            .finish_non_exhaustive()
4977    }
4978}
4979
4980impl StatefulWidget for StandardBottomSheet {
4981    type State = StandardBottomSheetState;
4982
4983    fn key(&self) -> Option<&KeyRef> {
4984        Some(&self.key)
4985    }
4986
4987    fn create_state(&self) -> StandardBottomSheetState {
4988        StandardBottomSheetState {
4989            state: StateData::new(),
4990            animation_curve: standard_bottom_sheet_curve(),
4991        }
4992    }
4993}
4994
4995/// Dart's `_StandardBottomSheetState`.
4996struct StandardBottomSheetState {
4997    state: StateData<StandardBottomSheet>,
4998    animation_curve: Rc<dyn Curve>,
4999}
5000
5001impl StandardBottomSheetState {
5002    fn close(self: Handle<Self>, app: &mut App) {
5003        let animation_controller = self.widget(app).animation_controller.clone();
5004        let on_closing = self.widget(app).on_closing.clone();
5005        animation_controller.reverse(app, None);
5006        if let Some(on_closing) = on_closing {
5007            on_closing(app);
5008        }
5009    }
5010
5011    fn handle_drag_start(self: Handle<Self>, app: &mut App, _details: DragStartDetails) {
5012        // Allow the bottom sheet to track the user's finger accurately.
5013        app.get_mut(self).animation_curve = Curves::linear();
5014    }
5015
5016    fn handle_drag_end(
5017        self: Handle<Self>,
5018        app: &mut App,
5019        _details: DragEndDetails,
5020        _is_closing: bool,
5021    ) {
5022        // Allow the bottom sheet to animate smoothly from its current position.
5023        let value = self.widget(app).animation_controller.value(app);
5024        app.get_mut(self).animation_curve = Rc::new(Split::new(
5025            value,
5026            Curves::linear(),
5027            standard_bottom_sheet_curve(),
5028        ));
5029    }
5030
5031    fn handle_status_change(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
5032        if status.is_dismissed()
5033            && let Some(on_dismissed) = self.widget(app).on_dismissed.clone()
5034        {
5035            on_dismissed(app);
5036        }
5037    }
5038
5039    fn extent_changed(
5040        self: Handle<Self>,
5041        app: &mut App,
5042        notification: &DraggableScrollableNotification,
5043    ) -> bool {
5044        let extent_remaining = 1.0 - notification.extent;
5045        let context = self.context(app);
5046        let scaffold = Scaffold::of(app, context);
5047        if extent_remaining < K_BOTTOM_SHEET_DOMINATES_PERCENTAGE {
5048            scaffold
5049                .floating_action_button_visibility_controller(app)
5050                .set_value(
5051                    app,
5052                    extent_remaining * K_BOTTOM_SHEET_DOMINATES_PERCENTAGE * 10.0,
5053                );
5054
5055            let scrim_animation_value =
5056                1.0 - extent_remaining / K_BOTTOM_SHEET_DOMINATES_PERCENTAGE;
5057            scaffold.show_body_scrim(app, true, scrim_animation_value);
5058        } else {
5059            scaffold
5060                .floating_action_button_visibility_controller(app)
5061                .set_value(app, 1.0);
5062            scaffold.show_body_scrim(app, false, 0.0);
5063        }
5064        // If the Scaffold.bottomSheet != null, we're a persistent bottom sheet.
5065        if (notification.extent - notification.min_extent).abs() < PRECISION_ERROR_TOLERANCE
5066            && scaffold.widget(app).bottom_sheet.is_none()
5067            && notification.should_close_on_min_extent
5068        {
5069            self.close(app);
5070        }
5071        false
5072    }
5073}
5074
5075impl State for StandardBottomSheetState {
5076    type Widget = StandardBottomSheet;
5077    waft_widgets::state_accessors!();
5078
5079    fn init_state(self: Handle<Self>, app: &mut App) {
5080        let animation_controller = self.widget(app).animation_controller.clone();
5081        debug_assert!(animation_controller.is_forward_or_completed(app));
5082        animation_controller.add_status_listener(
5083            app,
5084            AnimationStatusListener::handle_method(
5085                self,
5086                StandardBottomSheetState::handle_status_change,
5087            ),
5088        );
5089    }
5090
5091    fn dispose(self: Handle<Self>, app: &mut App) {
5092        let animation_controller = self.widget(app).animation_controller.clone();
5093        let on_dispose = self.widget(app).on_dispose.clone();
5094        animation_controller.remove_status_listener(
5095            app,
5096            &AnimationStatusListener::handle_method(
5097                self,
5098                StandardBottomSheetState::handle_status_change,
5099            ),
5100        );
5101        if let Some(on_dispose) = on_dispose {
5102            on_dispose(app);
5103        }
5104    }
5105
5106    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &StandardBottomSheet) {
5107        debug_assert!(self.widget(app).animation_controller == old_widget.animation_controller);
5108    }
5109
5110    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
5111        // Non-zero only while the keyboard lifts this sheet, see _ScaffoldLayout.
5112        let keyboard_inset = BottomSheetKeyboardInset::of(app, context);
5113        // The constraints describe the content, so they grow by the part of the
5114        // Material that extends behind the keyboard. This mirrors BottomSheet's own
5115        // lookup; its defaults, used when both are null, don't limit the height.
5116        let theme_constraints = Theme::of(app, context).bottom_sheet_theme.constraints;
5117        let widget = self.widget(app);
5118        let constraints = widget.constraints.or(theme_constraints);
5119
5120        let animation_controller = widget.animation_controller.clone();
5121        let is_persistent = widget.is_persistent;
5122        let builder = Rc::clone(&widget.builder);
5123        let mut bottom_sheet = BottomSheet::new(
5124            widget
5125                .on_closing
5126                .clone()
5127                .expect("a standard bottom sheet has an onClosing"),
5128            Rc::new(move |app: &mut App, context: BuildContext| {
5129                // Extends the Material behind the keyboard. Always present, so the
5130                // content keeps its state when the keyboard shows or hides.
5131                Padding::new(EdgeInsetsGeometry::only(0.0, 0.0, 0.0, keyboard_inset))
5132                    .child(builder(app, context))
5133                    .into_widget()
5134            }),
5135        )
5136        .animation_controller(animation_controller.clone())
5137        .enable_drag(widget.enable_drag)
5138        .on_drag_start(move |app: &mut App, details: DragStartDetails| {
5139            self.handle_drag_start(app, details)
5140        })
5141        .on_drag_end(
5142            move |app: &mut App, details: DragEndDetails, is_closing: bool| {
5143                self.handle_drag_end(app, details, is_closing)
5144            },
5145        );
5146        if let Some(show_drag_handle) = widget.show_drag_handle {
5147            bottom_sheet = bottom_sheet.show_drag_handle(show_drag_handle);
5148        }
5149        if let Some(background_color) = widget.background_color {
5150            bottom_sheet = bottom_sheet.background_color(background_color);
5151        }
5152        if let Some(elevation) = widget.elevation {
5153            bottom_sheet = bottom_sheet.elevation(elevation);
5154        }
5155        if let Some(shape) = widget.shape.clone() {
5156            bottom_sheet = bottom_sheet.shape(shape);
5157        }
5158        if let Some(clip_behavior) = widget.clip_behavior {
5159            bottom_sheet = bottom_sheet.clip_behavior(clip_behavior);
5160        }
5161        if let Some(constraints) = constraints {
5162            bottom_sheet = bottom_sheet.constraints(
5163                constraints
5164                    .min_height(constraints.min_height + keyboard_inset)
5165                    .max_height(constraints.max_height + keyboard_inset),
5166            );
5167        }
5168
5169        ListenableBuilder::new(
5170            Rc::new(animation_controller.erase::<AnyAnimation<f64>>()),
5171            move |app, _context, child| {
5172                let animation_curve = Rc::clone(&app.get(self).animation_curve);
5173                let mut align = Align::new()
5174                    .alignment(AlignmentDirectional::TOP_START.into())
5175                    .height_factor(animation_curve.transform(animation_controller.value(app)));
5176                if let Some(child) = child {
5177                    align = align.child(child.clone());
5178                }
5179                align.into_widget()
5180            },
5181        )
5182        .child({
5183            let mut semantics = Semantics::new().container(true);
5184            if !is_persistent {
5185                semantics = semantics.on_dismiss(Rc::new(move |app: &mut App| self.close(app)));
5186            }
5187            semantics.child(
5188                NotificationListener::<DraggableScrollableNotification>::new(bottom_sheet)
5189                    .on_notification(move |app, notification| {
5190                        self.extent_changed(app, notification)
5191                    })
5192                    .into_widget(),
5193            )
5194        })
5195        .into_widget()
5196    }
5197}
5198
5199/// A [`ScaffoldFeatureController`] for standard bottom sheets.
5200///
5201/// This is the type of objects returned by [`ScaffoldState::show_bottom_sheet`].
5202///
5203/// This controller is used to display both standard and persistent bottom
5204/// sheets. A bottom sheet is only persistent if it is set as the
5205/// [`Scaffold::bottom_sheet`].
5206pub struct PersistentBottomSheetController {
5207    /// The [`ScaffoldFeatureController`] this controller extends, over Dart's private
5208    /// `_StandardBottomSheet`; [`closed`](Self::closed), [`close`](Self::close) and
5209    /// [`set_state`](Self::set_state) reach it.
5210    feature: ScaffoldFeatureController<StandardBottomSheet, ()>,
5211    is_local_history_entry: bool,
5212}
5213
5214impl PersistentBottomSheetController {
5215    /// Completes when the bottom sheet is no longer visible.
5216    pub fn closed(&self) -> CompleterFuture<()> {
5217        self.feature.completer.future()
5218    }
5219
5220    /// Removes the bottom sheet from the scaffold.
5221    pub fn close(&self, app: &mut App) {
5222        (self.feature.close)(app);
5223    }
5224
5225    /// Marks the bottom sheet as needing to rebuild, after running `f`.
5226    pub fn set_state(&self, app: &mut App, f: &mut dyn FnMut(&mut App)) {
5227        if let Some(set_state) = &self.feature.set_state {
5228            set_state(app, f);
5229        }
5230    }
5231}
5232
5233impl Debug for PersistentBottomSheetController {
5234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5235        f.debug_struct("PersistentBottomSheetController")
5236            .field("isLocalHistoryEntry", &self.is_local_history_entry)
5237            .finish_non_exhaustive()
5238    }
5239}
5240
5241/// Dart's `_ScaffoldAspect`.
5242#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
5243enum ScaffoldAspect {
5244    Geometry,
5245    HasDrawer,
5246    DrawerExpanded,
5247    EndDrawerExpanded,
5248}
5249
5250/// Dart's `@internal scaffoldDrawerExpandedOf`.
5251pub(crate) fn scaffold_drawer_expanded_of(app: &mut App, context: BuildContext) -> Option<bool> {
5252    ScaffoldScope::inherit_from(app, context, Some(ScaffoldAspect::DrawerExpanded))
5253        .and_then(ScaffoldScope::drawer_expanded)
5254}
5255
5256/// Dart's `@internal scaffoldEndDrawerExpandedOf`.
5257pub(crate) fn scaffold_end_drawer_expanded_of(
5258    app: &mut App,
5259    context: BuildContext,
5260) -> Option<bool> {
5261    ScaffoldScope::inherit_from(app, context, Some(ScaffoldAspect::EndDrawerExpanded))
5262        .and_then(ScaffoldScope::end_drawer_expanded)
5263}
5264
5265/// Dart's `_ScaffoldScope`.
5266#[derive(Debug)]
5267struct ScaffoldScope {
5268    has_drawer: bool,
5269    has_end_drawer: bool,
5270    is_drawer_open: bool,
5271    is_end_drawer_open: bool,
5272    geometry_notifier: Ref<ScaffoldGeometryNotifier>,
5273    child: WidgetRef,
5274}
5275
5276impl ScaffoldScope {
5277    fn drawer_expanded(&self) -> Option<bool> {
5278        self.has_drawer.then_some(self.is_drawer_open)
5279    }
5280
5281    fn end_drawer_expanded(&self) -> Option<bool> {
5282        self.has_end_drawer.then_some(self.is_end_drawer_open)
5283    }
5284
5285    /// The erased widget: an [`InheritedModel`] has two `IntoWidget` impls, so the kind is
5286    /// named here.
5287    fn into_widget(self) -> WidgetRef {
5288        IntoWidget::<InheritedModelKind>::into_widget(self)
5289    }
5290}
5291
5292impl InheritedWidget for ScaffoldScope {
5293    fn child(&self) -> &WidgetRef {
5294        &self.child
5295    }
5296
5297    fn update_should_notify(&self, old_widget: &ScaffoldScope) -> bool {
5298        self.geometry_notifier != old_widget.geometry_notifier
5299            || self.has_drawer != old_widget.has_drawer
5300            || self.has_end_drawer != old_widget.has_end_drawer
5301            || self.is_drawer_open != old_widget.is_drawer_open
5302            || self.is_end_drawer_open != old_widget.is_end_drawer_open
5303    }
5304}
5305
5306impl InheritedModel for ScaffoldScope {
5307    type Aspect = ScaffoldAspect;
5308
5309    fn update_should_notify_dependent(
5310        &self,
5311        old_widget: &ScaffoldScope,
5312        dependencies: &HashSet<ScaffoldAspect>,
5313    ) -> bool {
5314        (dependencies.contains(&ScaffoldAspect::Geometry)
5315            && self.geometry_notifier != old_widget.geometry_notifier)
5316            || (dependencies.contains(&ScaffoldAspect::HasDrawer)
5317                && self.has_drawer != old_widget.has_drawer)
5318            || (dependencies.contains(&ScaffoldAspect::DrawerExpanded)
5319                && self.drawer_expanded() != old_widget.drawer_expanded())
5320            || (dependencies.contains(&ScaffoldAspect::EndDrawerExpanded)
5321                && self.end_drawer_expanded() != old_widget.end_drawer_expanded())
5322    }
5323}
5324
5325/// Dart's `_HitTestableAtOrigin`.
5326#[derive(Debug)]
5327struct HitTestableAtOrigin {
5328    global_key: GlobalKey,
5329}
5330
5331impl HitTestableAtOrigin {
5332    fn new(global_key: GlobalKey) -> HitTestableAtOrigin {
5333        HitTestableAtOrigin { global_key }
5334    }
5335
5336    fn hit_testable_at_origin(app: &mut App, key: &GlobalKey) -> bool {
5337        let Some(context) = key.current_context(app) else {
5338            debug_assert!(
5339                false,
5340                "BuildContext associated with {key:?} is not mounted. \
5341                 If you see this in a test, this is likely because the test was trying \
5342                 to simulate status bar tap on a non-iOS platform"
5343            );
5344            return false;
5345        };
5346        let render_object = context
5347            .find_render_object(app)
5348            .expect("a mounted MetaData has a render object")
5349            .as_box()
5350            .expect("MetaData creates a RenderMetaData");
5351        let view_id = View::of(app, context).id();
5352        let mut result = HitTestResult::new();
5353        GestureBinding::instance(app).hit_test_in_view(app, &mut result, Offset::ZERO, view_id);
5354        result.path().iter().any(|entry| {
5355            (entry.target() as &dyn Any)
5356                .downcast_ref::<BoxHitTestEntry>()
5357                .is_some_and(|entry| entry.target() == render_object)
5358        })
5359    }
5360}
5361
5362impl StatelessWidget for HitTestableAtOrigin {
5363    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
5364        MetaData::new()
5365            .key(self.global_key.clone().into())
5366            .behavior(HitTestBehavior::Translucent)
5367            .child(SizedBox::expand())
5368            .into_widget()
5369    }
5370}
5371
5372#[cfg(test)]
5373mod tests {
5374    //! The behaviour cases of `test/scaffold_test.dart`. Where Dart's widget is not ported, a
5375    //! case uses the widget's layout as Dart's has it: `placeholder` is Dart's `Placeholder`
5376    //! (a `LimitedBox` of 400 that fills what it is given).
5377
5378    use std::cell::{Cell, RefCell};
5379
5380    use waft_embedder::{Rect, TargetPlatform};
5381    use waft_painting::BorderSide;
5382    use waft_widgets::{
5383        Center, ColoredBox, Column, ConstrainedBox, CustomPaint, Directionality,
5384        DraggableScrollableController, DraggableScrollableSheet, LimitedBox, MediaQueryData,
5385        SingleChildScrollView,
5386    };
5387
5388    use waft_widgets::testing::{
5389        TargetPlatformVariant, WidgetTester, expect, find, finds_one_widget, test_widgets,
5390        test_widgets_variant,
5391    };
5392
5393    use super::*;
5394    use crate::elevated_button::ElevatedButton;
5395    use crate::test_support::material_app;
5396    use crate::text_button::TextButton;
5397    use crate::theme_data::ThemeData;
5398
5399    /// `tester.pumpWidget(MaterialApp(home: home(app)))`.
5400    fn pump_app(tester: &mut WidgetTester, home: impl FnOnce(&mut App) -> WidgetRef) {
5401        let root = {
5402            let mut app = tester.cell.borrow_mut();
5403            let theme = ThemeData::new(&app);
5404            material_app(theme, home(&mut app))
5405        };
5406        tester.pump_widget(root);
5407    }
5408
5409    /// Dart's `Directionality(textDirection: direction, child: MediaQuery(data: data, child:))`.
5410    fn directional(
5411        direction: TextDirection,
5412        data: MediaQueryData,
5413        child: impl IntoWidget<waft_widgets::StatefulKind>,
5414    ) -> WidgetRef {
5415        Directionality::new(direction, MediaQuery::new(data, child).into_widget()).into_widget()
5416    }
5417
5418    /// Dart's `Placeholder()`: a `LimitedBox(maxWidth: 400, maxHeight: 400)` around a
5419    /// `CustomPaint(size: Size.infinite)`, which fills what it is given.
5420    fn placeholder(key: Option<&GlobalKey>) -> WidgetRef {
5421        let mut limited = LimitedBox::new()
5422            .max_width(400.0)
5423            .max_height(400.0)
5424            .child(SizedBox::expand());
5425        if let Some(key) = key {
5426            limited = limited.key(key.clone().into());
5427        }
5428        limited.into_widget()
5429    }
5430
5431    fn rect_of(tester: &WidgetTester, key: &GlobalKey) -> Rect {
5432        let render = tester.render_object(key).as_box().expect("a render box");
5433        tester.global_rect(render)
5434    }
5435
5436    /// Dart's `tester.getCenter`/`getTopLeft`/`getBottomLeft`..: the point `at(size)` of
5437    /// `key`'s box, in global coordinates.
5438    fn point_of(tester: &WidgetTester, key: &GlobalKey, at: impl FnOnce(Size) -> Offset) -> Offset {
5439        let render = tester.render_object(key).as_box().expect("a render box");
5440        let app = tester.cell.borrow();
5441        let size = render.size(&app);
5442        render.local_to_global(&app, at(size), None)
5443    }
5444
5445    fn center_of(tester: &WidgetTester, key: &GlobalKey) -> Offset {
5446        point_of(tester, key, |size| size.center(Offset::ZERO))
5447    }
5448
5449    /// Dart's exact `Offset` comparison for a point the floating action button's scale and
5450    /// rotation transitions map: the host's matrices are f32, so the point is exact only to
5451    /// f32 (waft-widgets' `Matrix4Tween` entry).
5452    #[track_caller]
5453    fn assert_through_transforms(actual: Offset, expected: Offset) {
5454        assert!(
5455            (actual.dx() - expected.dx()).abs() < 1e-3
5456                && (actual.dy() - expected.dy()).abs() < 1e-3,
5457            "{} {} is not {} {}",
5458            actual.dx(),
5459            actual.dy(),
5460            expected.dx(),
5461            expected.dy()
5462        );
5463    }
5464
5465    fn size_of(tester: &WidgetTester, key: &GlobalKey) -> Size {
5466        rect_of(tester, key).size()
5467    }
5468
5469    /// Dart's `tester.state(find.byType(Scaffold))`, through the scaffold's key.
5470    fn scaffold_state(tester: &WidgetTester, key: &GlobalKey) -> Handle<ScaffoldState> {
5471        key.current_state::<ScaffoldState>(&tester.cell.borrow_mut())
5472            .expect("a mounted scaffold")
5473    }
5474
5475    fn transient_callback_count(tester: &WidgetTester) -> usize {
5476        waft_scheduler::SchedulerBinding::transient_callback_count(&mut tester.cell.borrow_mut())
5477    }
5478
5479    // 'extendBodyBehindAppBar change should not cause the body widget lose state'.
5480    #[test]
5481    fn switching_extend_body_behind_app_bar_keeps_the_bodys_state() {
5482        test_widgets(|tester| {
5483            // Regression test for https://github.com/flutter/flutter/issues/103741
5484            use waft_widgets::ScrollControllerLeaf;
5485            let controller = waft_widgets::ScrollController::default(&mut tester.cell.borrow_mut());
5486            let frame = |extend_body_behind_app_bar: bool| {
5487                directional(
5488                    TextDirection::Ltr,
5489                    MediaQueryData::new(),
5490                    Scaffold::new()
5491                        .extend_body_behind_app_bar(extend_body_behind_app_bar)
5492                        .resize_to_avoid_bottom_inset(false)
5493                        .body(
5494                            SingleChildScrollView::new()
5495                                .controller(controller.erase())
5496                                // Dart's `FlutterLogo(size: 1107)`: a box of that size.
5497                                .child(SizedBox::square(Some(1107.0))),
5498                        ),
5499                )
5500            };
5501            let pixels =
5502                |tester: &WidgetTester| controller.as_controller().offset(&tester.cell.borrow());
5503
5504            tester.pump_widget(frame(true));
5505            assert_eq!(pixels(tester), 0.0);
5506
5507            controller.jump_to(&mut tester.cell.borrow_mut(), 100.0);
5508            tester.pump();
5509            assert_eq!(pixels(tester), 100.0);
5510
5511            tester.pump_widget(frame(false));
5512            assert_eq!(pixels(tester), 100.0);
5513        });
5514    }
5515
5516    // 'Scaffold large bottom padding test'.
5517    #[test]
5518    fn a_keyboard_taller_than_the_scaffold_gives_the_body_no_height() {
5519        test_widgets(|tester| {
5520            let body_key = GlobalKey::new();
5521            let frame = |bottom: f64| {
5522                directional(
5523                    TextDirection::Ltr,
5524                    MediaQueryData::new().view_insets(EdgeInsets::only(0.0, 0.0, 0.0, bottom)),
5525                    Scaffold::new().body(Container::new().key(body_key.clone().into())),
5526                )
5527            };
5528            tester.pump_widget(frame(700.0));
5529            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 0.0));
5530
5531            tester.pump_widget(frame(500.0));
5532            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 100.0));
5533
5534            tester.pump_widget(boilerplate(
5535                MediaQuery::new(
5536                    MediaQueryData::new().view_insets(EdgeInsets::only(0.0, 0.0, 0.0, 580.0)),
5537                    with_title_app_bar(Scaffold::new())
5538                        .body(Container::new().key(body_key.clone().into())),
5539                )
5540                .into_widget(),
5541            ));
5542            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 0.0));
5543        });
5544    }
5545
5546    fn body_size_case(body: fn(&GlobalKey) -> WidgetRef) -> (Size, Offset) {
5547        let mut result = (Size::ZERO, Offset::ZERO);
5548        test_widgets(|tester| {
5549            let test_key = GlobalKey::new();
5550            tester.pump_widget(directional(
5551                TextDirection::Ltr,
5552                MediaQueryData::new(),
5553                Scaffold::new().body(body(&test_key)),
5554            ));
5555            let rect = rect_of(tester, &test_key);
5556            result = (rect.size(), rect.top_left());
5557        });
5558        result
5559    }
5560
5561    // 'body size with container'.
5562    #[test]
5563    fn a_container_body_fills_the_scaffold() {
5564        let (size, origin) =
5565            body_size_case(|key| Container::new().key(key.clone().into()).into_widget());
5566        assert_eq!(size, Size::new(800.0, 600.0));
5567        assert_eq!(origin, Offset::ZERO);
5568    }
5569
5570    // 'body size with sized container'.
5571    #[test]
5572    fn a_sized_container_body_keeps_its_height_at_the_top() {
5573        let (size, origin) = body_size_case(|key| {
5574            Container::new()
5575                .key(key.clone().into())
5576                .height(100.0)
5577                .into_widget()
5578        });
5579        assert_eq!(size, Size::new(800.0, 100.0));
5580        assert_eq!(origin, Offset::ZERO);
5581    }
5582
5583    // 'body size with centered container'.
5584    #[test]
5585    fn a_centered_container_body_fills_the_scaffold() {
5586        let (size, origin) = body_size_case(|key| {
5587            Center::new()
5588                .child(Container::new().key(key.clone().into()))
5589                .into_widget()
5590        });
5591        assert_eq!(size, Size::new(800.0, 600.0));
5592        assert_eq!(origin, Offset::ZERO);
5593    }
5594
5595    // 'body size with button'.
5596    #[test]
5597    fn a_button_body_keeps_its_minimum_size_at_the_top_left() {
5598        let (size, origin) = body_size_case(|key| {
5599            TextButton::new(
5600                Some(Listener::new(|_| {})),
5601                Some(waft_widgets::Text::new("")),
5602            )
5603            .key(key.clone().into())
5604            .into_widget()
5605        });
5606        assert_eq!(size, Size::new(64.0, 48.0));
5607        assert_eq!(origin, Offset::ZERO);
5608    }
5609
5610    // 'body size with extendBody'.
5611    #[test]
5612    fn extend_body_lays_the_body_out_under_the_bottom_navigation_bar() {
5613        test_widgets(|tester| {
5614            let body_key = GlobalKey::new();
5615            let media_query_bottom = Rc::new(Cell::new(f64::NAN));
5616            let frame = |tester: &WidgetTester,
5617                         extend_body: bool,
5618                         resize_to_avoid_bottom_inset: Option<bool>,
5619                         view_inset_bottom: f64| {
5620                let body_key = body_key.clone();
5621                let media_query_bottom = Rc::clone(&media_query_bottom);
5622                let mut scaffold = Scaffold::new()
5623                    .extend_body(extend_body)
5624                    .body(Builder::new(move |app, context| {
5625                        media_query_bottom.set(MediaQuery::padding_of(app, context).bottom);
5626                        Container::new().key(body_key.clone().into()).into_widget()
5627                    }))
5628                    // Dart's `BottomAppBar(child: SizedBox(height: 48.0))`, which Material 2
5629                    // lays out 48 tall; `BottomAppBar` is not ported.
5630                    .bottom_navigation_bar(SizedBox::new().height(48.0));
5631                if let Some(resize_to_avoid_bottom_inset) = resize_to_avoid_bottom_inset {
5632                    scaffold = scaffold.resize_to_avoid_bottom_inset(resize_to_avoid_bottom_inset);
5633                }
5634                let theme = ThemeData::builder()
5635                    .use_material3(false)
5636                    .build(&tester.cell.borrow());
5637                material_app(
5638                    theme,
5639                    MediaQuery::new(
5640                        MediaQueryData::new().view_insets(EdgeInsets::only(
5641                            0.0,
5642                            0.0,
5643                            0.0,
5644                            view_inset_bottom,
5645                        )),
5646                        scaffold,
5647                    )
5648                    .into_widget(),
5649                )
5650            };
5651
5652            tester.pump_widget(frame(tester, true, None, 0.0));
5653            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 600.0));
5654            assert_eq!(media_query_bottom.get(), 48.0);
5655
5656            tester.pump_widget(frame(tester, false, None, 0.0));
5657            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 552.0)); // 552 = 600 - 48 (BAB height)
5658            assert_eq!(media_query_bottom.get(), 0.0);
5659
5660            // If resizeToAvoidBottomInsets is false, same results as if it was unspecified (null).
5661            tester.pump_widget(frame(tester, true, Some(false), 100.0));
5662            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 600.0));
5663            assert_eq!(media_query_bottom.get(), 48.0);
5664
5665            tester.pump_widget(frame(tester, false, Some(false), 100.0));
5666            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 552.0));
5667            assert_eq!(media_query_bottom.get(), 0.0);
5668
5669            // If resizeToAvoidBottomInsets is true and viewInsets.bottom is > the bottom
5670            // navigation bar's height then the body always resizes and the MediaQuery
5671            // isn't adjusted. This case corresponds to the keyboard appearing.
5672            tester.pump_widget(frame(tester, true, Some(true), 100.0));
5673            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 500.0));
5674            assert_eq!(media_query_bottom.get(), 0.0);
5675
5676            tester.pump_widget(frame(tester, false, Some(true), 100.0));
5677            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 500.0));
5678            assert_eq!(media_query_bottom.get(), 0.0);
5679        });
5680    }
5681
5682    // 'body size with extendBodyBehindAppBar'.
5683    #[test]
5684    fn extend_body_behind_app_bar_lays_the_body_out_under_the_app_bar() {
5685        test_widgets(|tester| {
5686            let app_bar_key = GlobalKey::new();
5687            let body_key = GlobalKey::new();
5688
5689            const APP_BAR_HEIGHT: f64 = 100.0;
5690            const WINDOW_PADDING_TOP: f64 = 24.0;
5691            let media_query_top = Rc::new(Cell::new(f64::NAN));
5692
5693            let frame = |extend_body_behind_app_bar: bool,
5694                         has_app_bar: bool,
5695                         fixed_height_app_bar: bool| {
5696                let body_key = body_key.clone();
5697                let media_query_top = Rc::clone(&media_query_top);
5698                let mut scaffold = Scaffold::new()
5699                    .extend_body_behind_app_bar(extend_body_behind_app_bar)
5700                    .body(Builder::new(move |app, context| {
5701                        media_query_top.set(MediaQuery::padding_of(app, context).top);
5702                        Container::new().key(body_key.clone().into()).into_widget()
5703                    }));
5704                if has_app_bar {
5705                    scaffold = scaffold.app_bar(PreferredSizeWidgetRef::new(
5706                        waft_widgets::PreferredSize::new(
5707                            Size::from_height(APP_BAR_HEIGHT),
5708                            Container::new().constraints(
5709                                BoxConstraints::new().min_height(APP_BAR_HEIGHT).max_height(
5710                                    if fixed_height_app_bar {
5711                                        APP_BAR_HEIGHT
5712                                    } else {
5713                                        f64::INFINITY
5714                                    },
5715                                ),
5716                            ),
5717                        )
5718                        .key(app_bar_key.clone().into()),
5719                    ));
5720                }
5721                directional(
5722                    TextDirection::Ltr,
5723                    MediaQueryData::new().padding(EdgeInsets::only(
5724                        0.0,
5725                        WINDOW_PADDING_TOP,
5726                        0.0,
5727                        0.0,
5728                    )),
5729                    scaffold,
5730                )
5731            };
5732            let app_bar_found = |tester: &WidgetTester| {
5733                let app = tester.cell.borrow();
5734                app_bar_key.current_context(&app).is_some()
5735            };
5736
5737            // When an appbar is provided, the Scaffold's body is built within a
5738            // MediaQuery with padding.top = 0, and the appBar's maxHeight is
5739            // constrained to its preferredSize.height + the original MediaQuery
5740            // padding.top. When extendBodyBehindAppBar is true, an additional
5741            // inner MediaQuery is added around the Scaffold's body with padding.top
5742            // equal to the overall height of the appBar. See _BodyBuilder in
5743            // material/scaffold.dart.
5744
5745            tester.pump_widget(frame(true, true, false));
5746            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 600.0));
5747            assert_eq!(
5748                size_of(tester, &app_bar_key),
5749                Size::new(800.0, APP_BAR_HEIGHT + WINDOW_PADDING_TOP)
5750            );
5751            assert_eq!(media_query_top.get(), APP_BAR_HEIGHT + WINDOW_PADDING_TOP);
5752
5753            tester.pump_widget(frame(true, false, false));
5754            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 600.0));
5755            assert!(!app_bar_found(tester));
5756            assert_eq!(media_query_top.get(), WINDOW_PADDING_TOP);
5757
5758            tester.pump_widget(frame(false, true, false));
5759            assert_eq!(
5760                size_of(tester, &body_key),
5761                Size::new(800.0, 600.0 - APP_BAR_HEIGHT - WINDOW_PADDING_TOP)
5762            );
5763            assert_eq!(
5764                size_of(tester, &app_bar_key),
5765                Size::new(800.0, APP_BAR_HEIGHT + WINDOW_PADDING_TOP)
5766            );
5767            assert_eq!(media_query_top.get(), 0.0);
5768
5769            tester.pump_widget(frame(false, false, false));
5770            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 600.0));
5771            assert!(!app_bar_found(tester));
5772            assert_eq!(media_query_top.get(), WINDOW_PADDING_TOP);
5773
5774            tester.pump_widget(frame(true, true, true));
5775            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 600.0));
5776            assert_eq!(
5777                size_of(tester, &app_bar_key),
5778                Size::new(800.0, APP_BAR_HEIGHT)
5779            );
5780            assert_eq!(media_query_top.get(), APP_BAR_HEIGHT);
5781
5782            tester.pump_widget(frame(true, false, true));
5783            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 600.0));
5784            assert!(!app_bar_found(tester));
5785            assert_eq!(media_query_top.get(), WINDOW_PADDING_TOP);
5786
5787            tester.pump_widget(frame(false, true, true));
5788            assert_eq!(
5789                size_of(tester, &body_key),
5790                Size::new(800.0, 600.0 - APP_BAR_HEIGHT)
5791            );
5792            assert_eq!(
5793                size_of(tester, &app_bar_key),
5794                Size::new(800.0, APP_BAR_HEIGHT)
5795            );
5796            assert_eq!(media_query_top.get(), 0.0);
5797
5798            tester.pump_widget(frame(false, false, true));
5799            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 600.0));
5800            assert!(!app_bar_found(tester));
5801            assert_eq!(media_query_top.get(), WINDOW_PADDING_TOP);
5802        });
5803    }
5804
5805    // 'Nested scaffold body insets'.
5806    #[test]
5807    fn nested_scaffolds_inset_the_body_unless_both_opt_out() {
5808        test_widgets(|tester| {
5809            let body_key = GlobalKey::new();
5810            let frame = |inner: Option<bool>, outer: Option<bool>| {
5811                let body_key = body_key.clone();
5812                let mut inner_scaffold =
5813                    Scaffold::new().body(Container::new().key(body_key.into()));
5814                if let Some(inner) = inner {
5815                    inner_scaffold = inner_scaffold.resize_to_avoid_bottom_inset(inner);
5816                }
5817                let inner_scaffold = Rc::new(std::cell::RefCell::new(Some(inner_scaffold)));
5818                let mut outer_scaffold =
5819                    Scaffold::new().body(Builder::new(move |_app, _context| {
5820                        inner_scaffold
5821                            .borrow_mut()
5822                            .take()
5823                            .map(IntoWidget::into_widget)
5824                            .unwrap_or_else(|| SizedBox::shrink().into_widget())
5825                    }));
5826                if let Some(outer) = outer {
5827                    outer_scaffold = outer_scaffold.resize_to_avoid_bottom_inset(outer);
5828                }
5829                directional(
5830                    TextDirection::Ltr,
5831                    MediaQueryData::new().view_insets(EdgeInsets::only(0.0, 0.0, 0.0, 100.0)),
5832                    outer_scaffold,
5833                )
5834            };
5835            for (inner, outer, height) in [
5836                (Some(true), Some(true), 500.0),
5837                (Some(false), Some(true), 500.0),
5838                (Some(true), Some(false), 500.0),
5839                // This is the only case where the body is not bottom inset.
5840                (Some(false), Some(false), 600.0),
5841                // resizeToAvoidBottomInset default is true
5842                (None, None, 500.0),
5843                (None, Some(false), 500.0),
5844                (Some(false), None, 500.0),
5845            ] {
5846                tester.pump_widget(frame(inner, outer));
5847                assert_eq!(
5848                    size_of(tester, &body_key),
5849                    Size::new(800.0, height),
5850                    "inner {inner:?}, outer {outer:?}"
5851                );
5852            }
5853        });
5854    }
5855
5856    // 'Floating action button directionality'.
5857    #[test]
5858    fn the_floating_action_button_sits_at_the_end_for_the_text_direction() {
5859        test_widgets(|tester| {
5860            let fab_key = GlobalKey::new();
5861            let frame = |direction: TextDirection| {
5862                directional(
5863                    direction,
5864                    MediaQueryData::new().view_insets(EdgeInsets::only(0.0, 0.0, 0.0, 200.0)),
5865                    Scaffold::new().floating_action_button(
5866                        FloatingActionButton::new(None)
5867                            .key(fab_key.clone().into())
5868                            .child(waft_widgets::Text::new("1")),
5869                    ),
5870                )
5871            };
5872            tester.pump_widget(frame(TextDirection::Ltr));
5873            assert_through_transforms(center_of(tester, &fab_key), Offset::new(756.0, 356.0));
5874
5875            tester.pump_widget(frame(TextDirection::Rtl));
5876            assert_eq!(transient_callback_count(tester), 0);
5877            assert_through_transforms(center_of(tester, &fab_key), Offset::new(44.0, 356.0));
5878        });
5879    }
5880
5881    // 'Floating Action Button bottom padding not consumed by viewInsets'.
5882    #[test]
5883    fn the_keyboard_does_not_consume_the_floating_action_buttons_bottom_view_padding() {
5884        test_widgets(|tester| {
5885            let fab_key = GlobalKey::new();
5886            let frame = |data: MediaQueryData| {
5887                directional(
5888                    TextDirection::Ltr,
5889                    data,
5890                    Scaffold::new()
5891                        .resize_to_avoid_bottom_inset(false)
5892                        .body(Container::new())
5893                        .floating_action_button(placeholder(Some(&fab_key))),
5894                )
5895            };
5896            tester.pump_widget(frame(
5897                MediaQueryData::new().view_padding(EdgeInsets::only(0.0, 0.0, 0.0, 20.0)),
5898            ));
5899            let initial_point = center_of(tester, &fab_key);
5900            let bottom_left = point_of(tester, &fab_key, |size| size.bottom_left(Offset::ZERO));
5901            assert_through_transforms(
5902                Offset::new(
5903                    bottom_left.dx(),
5904                    600.0 - 20.0 - crate::K_FLOATING_ACTION_BUTTON_MARGIN,
5905                ),
5906                bottom_left,
5907            );
5908
5909            // Consume bottom padding - as if by the keyboard opening
5910            tester.pump_widget(frame(
5911                MediaQueryData::new()
5912                    .view_padding(EdgeInsets::only(0.0, 0.0, 0.0, 20.0))
5913                    .view_insets(EdgeInsets::only(0.0, 0.0, 0.0, 300.0)),
5914            ));
5915            let final_point = center_of(tester, &fab_key);
5916            assert_eq!(initial_point, final_point);
5917        });
5918    }
5919
5920    // 'viewPadding change should trigger _ScaffoldLayout re-layout'.
5921    #[test]
5922    fn a_view_padding_change_lays_the_scaffold_out_again() {
5923        test_widgets(|tester| {
5924            let frame = |bottom: f64| {
5925                directional(
5926                    TextDirection::Ltr,
5927                    MediaQueryData::new().view_padding(EdgeInsets::only(0.0, 0.0, 0.0, bottom)),
5928                    Scaffold::new()
5929                        .resize_to_avoid_bottom_inset(false)
5930                        .body(Container::new())
5931                        .floating_action_button(placeholder(None)),
5932                )
5933            };
5934            tester.pump_widget(frame(300.0));
5935            let layout = tester.first::<waft_rendering::RenderCustomMultiChildLayoutBox>();
5936            assert!(
5937                !waft_rendering::RenderBox::as_object(layout)
5938                    .debug_needs_layout(&tester.cell.borrow())
5939            );
5940
5941            // Dart's `pumpWidget(.., phase: EnginePhase.build)`: build without laying out.
5942            {
5943                let mut app = tester.cell.borrow_mut();
5944                let view = app.platform().views().into_iter().next().expect("one view");
5945                let root = waft_widgets::View::new(view, frame(400.0)).into_widget();
5946                let binding = WidgetsBinding::instance(&mut app);
5947                binding.attach_root_widget(&mut app, root);
5948                let root_element = binding.root_element(&app).expect("a root element");
5949                let build_owner = binding.build_owner(&app);
5950                build_owner.build_scope(&mut app, root_element, None);
5951            }
5952            assert!(
5953                waft_rendering::RenderBox::as_object(layout)
5954                    .debug_needs_layout(&tester.cell.borrow())
5955            );
5956        });
5957    }
5958
5959    // 'BottomSheet bottom padding is not consumed by viewInsets'.
5960    #[test]
5961    fn the_keyboard_does_not_move_a_bottom_sheet_that_does_not_avoid_it() {
5962        test_widgets(|tester| {
5963            let sheet_key = GlobalKey::new();
5964            let frame = |data: MediaQueryData| {
5965                directional(
5966                    TextDirection::Ltr,
5967                    data,
5968                    Scaffold::new()
5969                        .resize_to_avoid_bottom_inset(false)
5970                        .body(Container::new())
5971                        .bottom_sheet(placeholder(Some(&sheet_key))),
5972                )
5973            };
5974            tester.pump_widget(frame(
5975                MediaQueryData::new().padding(EdgeInsets::only(0.0, 0.0, 0.0, 20.0)),
5976            ));
5977            let initial_point = center_of(tester, &sheet_key);
5978            // Consume bottom padding - as if by the keyboard opening
5979            tester.pump_widget(frame(
5980                MediaQueryData::new()
5981                    .view_padding(EdgeInsets::only(0.0, 0.0, 0.0, 20.0))
5982                    .view_insets(EdgeInsets::only(0.0, 0.0, 0.0, 300.0)),
5983            ));
5984            let final_point = center_of(tester, &sheet_key);
5985            assert_eq!(initial_point, final_point);
5986        });
5987    }
5988
5989    fn tall_body() -> WidgetRef {
5990        SingleChildScrollView::new()
5991            .child(
5992                Container::new()
5993                    .color(Colors::AMBER.primary())
5994                    .height(5000.0)
5995                    .child(waft_widgets::Text::new("body")),
5996            )
5997            .into_widget()
5998    }
5999
6000    fn center_of_element(tester: &WidgetTester, element: waft_widgets::AnyElement) -> Offset {
6001        tester.get_rect(element).center()
6002    }
6003
6004    // 'Persistent bottom buttons are persistent'.
6005    #[test]
6006    fn persistent_footer_buttons_stay_tappable_after_the_body_scrolls() {
6007        test_widgets(|tester| {
6008            let did_press_button = Rc::new(Cell::new(false));
6009            pump_app(tester, |_app| {
6010                let did_press_button = Rc::clone(&did_press_button);
6011                Scaffold::new()
6012                    .body(tall_body())
6013                    .persistent_footer_buttons(vec![
6014                        TextButton::new(
6015                            Some(Listener::new(move |_| did_press_button.set(true))),
6016                            Some(waft_widgets::Text::new("X")),
6017                        )
6018                        .into_widget(),
6019                    ])
6020                    .into_widget()
6021            });
6022
6023            let scroll_view = find::by_type::<SingleChildScrollView>().evaluate(tester)[0];
6024            let start = center_of_element(tester, scroll_view);
6025            tester.drag_from(start, Offset::new(0.0, -1000.0), 1);
6026            tester.pump();
6027            assert!(!did_press_button.get());
6028            let x = find::text("X").evaluate(tester)[0];
6029            let at = center_of_element(tester, x);
6030            tester.tap_at(at, 2);
6031            assert!(did_press_button.get());
6032        });
6033    }
6034
6035    // 'Persistent bottom buttons alignment'.
6036    #[test]
6037    fn persistent_footer_buttons_follow_the_footer_alignment() {
6038        test_widgets(|tester| {
6039            let build_app = |tester: &mut WidgetTester, alignment: AlignmentDirectional| {
6040                pump_app(tester, |_app| {
6041                    Scaffold::new()
6042                        .body(tall_body())
6043                        .persistent_footer_alignment(alignment)
6044                        .persistent_footer_buttons(vec![
6045                            TextButton::new(
6046                                Some(Listener::new(|_| {})),
6047                                Some(waft_widgets::Text::new("X")),
6048                            )
6049                            .into_widget(),
6050                        ])
6051                        .into_widget()
6052                });
6053            };
6054            let footer_button = |tester: &WidgetTester| {
6055                let button = find::by_type::<TextButton>().evaluate(tester)[0];
6056                tester.get_rect(button)
6057            };
6058
6059            build_app(tester, AlignmentDirectional::CENTER_END);
6060            assert_eq!(footer_button(tester).right, 800.0 - 8.0);
6061
6062            build_app(tester, AlignmentDirectional::CENTER);
6063            assert_eq!(footer_button(tester).center().dx(), 800.0 / 2.0);
6064
6065            build_app(tester, AlignmentDirectional::CENTER_START);
6066            assert_eq!(footer_button(tester).left, 8.0);
6067        });
6068    }
6069
6070    /// Dart's `find.ancestor(of: find.byType(OverflowBar), matching: find.byType(W)).first`.
6071    fn overflow_bar_ancestor<W: 'static>(tester: &WidgetTester) -> waft_widgets::AnyElement {
6072        let overflow_bar = find::by_type::<OverflowBar>().evaluate(tester)[0];
6073        tester.ancestor_of_type::<W>(overflow_bar)
6074    }
6075
6076    // 'Persistent bottom buttons apply media padding'.
6077    #[test]
6078    fn persistent_footer_buttons_apply_the_media_padding() {
6079        test_widgets(|tester| {
6080            tester.pump_widget(directional(
6081                TextDirection::Ltr,
6082                MediaQueryData::new().padding(EdgeInsets::only(10.0, 20.0, 30.0, 40.0)),
6083                Scaffold::new()
6084                    .body(tall_body())
6085                    .persistent_footer_buttons(vec![placeholder(None)]),
6086            ));
6087
6088            let buttons_bar = overflow_bar_ancestor::<Padding>(tester);
6089            let rect = tester.get_rect(buttons_bar);
6090            assert_eq!(rect.bottom_left(), Offset::new(10.0, 560.0));
6091            assert_eq!(rect.bottom_right(), Offset::new(770.0, 560.0));
6092        });
6093    }
6094
6095    // 'Persistent bottom buttons bottom padding is not consumed by viewInsets'.
6096    #[test]
6097    fn the_keyboard_does_not_move_persistent_footer_buttons_that_do_not_avoid_it() {
6098        test_widgets(|tester| {
6099            let button_key = GlobalKey::new();
6100            let frame = |data: MediaQueryData| {
6101                directional(
6102                    TextDirection::Ltr,
6103                    data,
6104                    Scaffold::new()
6105                        .resize_to_avoid_bottom_inset(false)
6106                        .body(Container::new())
6107                        .persistent_footer_buttons(vec![placeholder(Some(&button_key))]),
6108                )
6109            };
6110            tester.pump_widget(frame(
6111                MediaQueryData::new().padding(EdgeInsets::only(0.0, 0.0, 0.0, 20.0)),
6112            ));
6113            let initial_point = center_of(tester, &button_key);
6114            // Consume bottom padding - as if by the keyboard opening
6115            tester.pump_widget(frame(
6116                MediaQueryData::new()
6117                    .view_padding(EdgeInsets::only(0.0, 0.0, 0.0, 20.0))
6118                    .view_insets(EdgeInsets::only(0.0, 0.0, 0.0, 300.0)),
6119            ));
6120            let final_point = center_of(tester, &button_key);
6121            assert_eq!(initial_point, final_point);
6122        });
6123    }
6124
6125    // 'Persistent bottom buttons can apply decoration'.
6126    #[test]
6127    fn persistent_footer_buttons_take_the_footer_decoration() {
6128        test_widgets(|tester| {
6129            tester.pump_widget(directional(
6130                TextDirection::Ltr,
6131                MediaQueryData::new().padding(EdgeInsets::only(10.0, 20.0, 30.0, 40.0)),
6132                Scaffold::new()
6133                    .body(tall_body())
6134                    .persistent_footer_decoration(BoxDecoration::new().border(Border {
6135                        top: BorderSide {
6136                            color: Colors::RED.primary(),
6137                            ..BorderSide::default()
6138                        },
6139                        ..Border::default()
6140                    }))
6141                    .persistent_footer_buttons(vec![placeholder(None)]),
6142            ));
6143
6144            let persistent_footer = overflow_bar_ancestor::<Container>(tester);
6145            let top_color = tester.widget(persistent_footer, |container: &Container| {
6146                let decoration = container.decoration.as_ref().expect("a decoration");
6147                let decoration = decoration
6148                    .as_any()
6149                    .downcast_ref::<BoxDecoration>()
6150                    .expect("a BoxDecoration");
6151                decoration.border.as_ref().expect("a border").top().color
6152            });
6153            assert_eq!(top_color, Colors::RED.primary());
6154        });
6155    }
6156
6157    // 'Scaffold background color defaults to ColorScheme.surface'.
6158    #[test]
6159    fn the_background_colour_defaults_to_the_colour_schemes_surface() {
6160        test_widgets(|tester| {
6161            let theme = {
6162                let app = tester.cell.borrow();
6163                let base = ThemeData::new(&app);
6164                #[allow(deprecated)]
6165                let color_scheme = base
6166                    .color_scheme
6167                    .copy_with()
6168                    .with_surface(Colors::ORANGE.primary())
6169                    .with_background(Colors::GREEN.primary());
6170                ThemeData::builder().color_scheme(color_scheme).build(&app)
6171            };
6172            let surface = theme.color_scheme.surface();
6173            let root = material_app(
6174                theme,
6175                Scaffold::new().body(SizedBox::expand()).into_widget(),
6176            );
6177            tester.pump_widget(root);
6178
6179            let scaffold = find::by_type::<Scaffold>().evaluate(tester)[0];
6180            let material = *find::by_type::<Material>()
6181                .evaluate(tester)
6182                .iter()
6183                .find(|material| tester.ancestors(**material).contains(&scaffold))
6184                .expect("the scaffold's material");
6185            let color = tester.widget(material, |material: &Material| material.color);
6186            assert_eq!(color, Some(surface));
6187        });
6188    }
6189
6190    // 'Body height remains Scaffold height when keyboard is smaller than bottomNavigationBar
6191    // and extendBody is true'.
6192    #[test]
6193    fn an_extended_body_keeps_the_scaffolds_height_under_a_keyboard_shorter_than_the_bar() {
6194        test_widgets(|tester| {
6195            let body_key = GlobalKey::new();
6196            let frame = |tester: &mut WidgetTester, keyboard_height: f64| {
6197                let body_key = body_key.clone();
6198                pump_app(tester, move |_app| {
6199                    Builder::new(move |app, context| {
6200                        MediaQuery::new(
6201                            MediaQuery::of(app, context)
6202                                .copy_with()
6203                                .view_insets(EdgeInsets::only(0.0, 0.0, 0.0, keyboard_height)),
6204                            Scaffold::new()
6205                                .extend_body(true)
6206                                .body(SizedBox::expand().key(body_key.clone().into()))
6207                                .bottom_navigation_bar(SizedBox::new().height(100.0)),
6208                        )
6209                        .into_widget()
6210                    })
6211                    .into_widget()
6212                });
6213            };
6214
6215            frame(tester, 0.0);
6216            assert_eq!(size_of(tester, &body_key).height(), 600.0);
6217
6218            frame(tester, 100.0);
6219            assert_eq!(size_of(tester, &body_key).height(), 600.0);
6220
6221            frame(tester, 200.0);
6222            assert_eq!(size_of(tester, &body_key).height(), 400.0);
6223        });
6224    }
6225
6226    /// What a drawer callback last said, Dart's captured `bool`.
6227    #[derive(Clone, Default)]
6228    struct Flag(Rc<Cell<bool>>);
6229
6230    impl Flag {
6231        fn setter(&self) -> impl Fn(&mut App, bool) + 'static {
6232            let flag = Rc::clone(&self.0);
6233            move |_app, value| flag.set(value)
6234        }
6235
6236        fn get(&self) -> bool {
6237            self.0.get()
6238        }
6239    }
6240
6241    fn drawer_scaffold(
6242        key: &GlobalKey,
6243        is_drawer_open: &Flag,
6244        is_end_drawer_open: &Flag,
6245    ) -> Scaffold {
6246        Scaffold::new()
6247            .key(key.clone().into())
6248            .drawer(Container::new().color(Colors::BLUE.primary()))
6249            .on_drawer_changed(is_drawer_open.setter())
6250            .end_drawer(Container::new().color(Colors::GREEN.primary()))
6251            .on_end_drawer_changed(is_end_drawer_open.setter())
6252            .body(Container::new())
6253    }
6254
6255    // 'Scaffold drawer callback test'.
6256    #[test]
6257    fn opening_one_drawer_closes_the_other_and_reports_both() {
6258        test_widgets(|tester| {
6259            let key = GlobalKey::new();
6260            let (is_drawer_open, is_end_drawer_open) = (Flag::default(), Flag::default());
6261            pump_app(tester, |_app| {
6262                drawer_scaffold(&key, &is_drawer_open, &is_end_drawer_open).into_widget()
6263            });
6264            let scaffold_state = scaffold_state(tester, &key);
6265
6266            scaffold_state.open_drawer(&mut tester.cell.borrow_mut());
6267            tester.pump_and_settle();
6268            assert!(is_drawer_open.get());
6269            scaffold_state.open_end_drawer(&mut tester.cell.borrow_mut());
6270            tester.pump_and_settle();
6271            assert!(!is_drawer_open.get());
6272
6273            scaffold_state.open_end_drawer(&mut tester.cell.borrow_mut());
6274            tester.pump_and_settle();
6275            assert!(is_end_drawer_open.get());
6276            scaffold_state.open_drawer(&mut tester.cell.borrow_mut());
6277            tester.pump_and_settle();
6278            assert!(!is_end_drawer_open.get());
6279        });
6280    }
6281
6282    // 'Scaffold drawer callback test - only call when changed'.
6283    #[test]
6284    fn a_fling_too_short_to_open_a_drawer_calls_no_drawer_callback() {
6285        test_widgets(|tester| {
6286            let key = GlobalKey::new();
6287            let on_drawer_changed_called = Flag::default();
6288            let on_end_drawer_changed_called = Flag::default();
6289            pump_app(tester, |_app| {
6290                let drawer_called = Rc::clone(&on_drawer_changed_called.0);
6291                let end_drawer_called = Rc::clone(&on_end_drawer_changed_called.0);
6292                Scaffold::new()
6293                    .key(key.clone().into())
6294                    .drawer(Container::new().color(Colors::BLUE.primary()))
6295                    .on_drawer_changed(move |_app, _is_open| drawer_called.set(true))
6296                    .end_drawer(Container::new().color(Colors::GREEN.primary()))
6297                    .on_end_drawer_changed(move |_app, _is_open| end_drawer_called.set(true))
6298                    .body(Container::new())
6299                    .into_widget()
6300            });
6301
6302            tester.fling_from(Offset::ZERO, Offset::new(10.0, 0.0), 10.0, 1);
6303            assert!(!on_drawer_changed_called.get());
6304
6305            tester.pump_and_settle();
6306
6307            let width = WidgetTester::SIZE.width();
6308            tester.fling_from(
6309                Offset::new(width - 1.0, 0.0),
6310                Offset::new(-10.0, 0.0),
6311                10.0,
6312                2,
6313            );
6314            tester.pump_and_settle();
6315            assert!(!on_end_drawer_changed_called.get());
6316        });
6317    }
6318
6319    // 'Drawer can be dismissed with escape keyboard shortcut'.
6320    #[test]
6321    fn the_escape_key_dismisses_an_open_drawer() {
6322        test_widgets(|tester| {
6323            let key = GlobalKey::new();
6324            let (is_drawer_open, is_end_drawer_open) = (Flag::default(), Flag::default());
6325            pump_app(tester, |_app| {
6326                drawer_scaffold(&key, &is_drawer_open, &is_end_drawer_open).into_widget()
6327            });
6328            let scaffold_state = scaffold_state(tester, &key);
6329            let escape = |tester: &mut WidgetTester| {
6330                tester.send_key_event(
6331                    waft_services::PhysicalKeyboardKey::ESCAPE,
6332                    waft_services::LogicalKeyboardKey::ESCAPE,
6333                );
6334            };
6335
6336            scaffold_state.open_drawer(&mut tester.cell.borrow_mut());
6337            tester.pump_and_settle();
6338            assert!(is_drawer_open.get());
6339            assert!(!is_end_drawer_open.get());
6340
6341            // Try to dismiss the drawer with the shortcut key
6342            escape(tester);
6343            tester.pump_and_settle();
6344            assert!(!is_drawer_open.get());
6345            assert!(!is_end_drawer_open.get());
6346
6347            scaffold_state.open_end_drawer(&mut tester.cell.borrow_mut());
6348            tester.pump_and_settle();
6349            assert!(!is_drawer_open.get());
6350            assert!(is_end_drawer_open.get());
6351
6352            // Try to dismiss the drawer with the shortcut key
6353            escape(tester);
6354            tester.pump_and_settle();
6355            assert!(!is_drawer_open.get());
6356            assert!(!is_end_drawer_open.get());
6357        });
6358    }
6359
6360    /// `AppBar(centerTitle: true, title: Text('Title'))`, the app bar of Dart's drawer cases.
6361    fn centered_title_app_bar() -> PreferredSizeWidgetRef {
6362        PreferredSizeWidgetRef::new(
6363            AppBar::new()
6364                .center_title(true)
6365                .title(waft_widgets::Text::new("Title")),
6366        )
6367    }
6368
6369    /// `Scaffold(drawer: Drawer(child: Text('Drawer')), body: Text(body), appBar:
6370    /// AppBar(centerTitle: true, title: Text('Title')))`.
6371    fn text_drawer_scaffold(key: &GlobalKey, body: &str) -> Scaffold {
6372        Scaffold::new()
6373            .key(key.clone().into())
6374            .drawer(crate::drawer::Drawer::new().child(waft_widgets::Text::new("Drawer")))
6375            .body(waft_widgets::Text::new(body))
6376            .app_bar(centered_title_app_bar())
6377    }
6378
6379    /// Dart's `tester.tap(find.byType(IconButton).first)`: the app bar's drawer button.
6380    fn tap_first_icon_button(tester: &mut WidgetTester, pointer: i64) {
6381        let button = *find::by_type::<crate::icon_button::IconButton>()
6382            .evaluate(tester)
6383            .first()
6384            .expect("an IconButton");
6385        let at = center_of_element(tester, button);
6386        tester.tap_at(at, pointer);
6387    }
6388
6389    // 'Drawer opens correctly with custom edgeDragWidth' .
6390    #[test]
6391    fn a_wider_edge_drag_width_opens_the_drawer_from_further_in() {
6392        test_widgets(|tester| {
6393            let key = GlobalKey::new();
6394            // The default edge drag width is 20.0.
6395            pump_app(tester, |_app| {
6396                text_drawer_scaffold(&key, "Scaffold body").into_widget()
6397            });
6398            let scaffold_state = scaffold_state(tester, &key);
6399            assert!(!scaffold_state.is_drawer_open(&tester.cell.borrow()));
6400
6401            tester.drag_from(Offset::new(35.0, 100.0), Offset::new(300.0, 0.0), 1);
6402            tester.pump_and_settle();
6403            assert!(!scaffold_state.is_drawer_open(&tester.cell.borrow()));
6404
6405            pump_app(tester, |_app| {
6406                text_drawer_scaffold(&key, "Scaffold Body")
6407                    .drawer_edge_drag_width(40.0)
6408                    .into_widget()
6409            });
6410            let scaffold_state = self::scaffold_state(tester, &key);
6411            assert!(!scaffold_state.is_drawer_open(&tester.cell.borrow()));
6412
6413            tester.drag_from(Offset::new(35.0, 100.0), Offset::new(300.0, 0.0), 2);
6414            tester.pump_and_settle();
6415            assert!(scaffold_state.is_drawer_open(&tester.cell.borrow()));
6416        });
6417    }
6418
6419    const SIMULATED_NOTCH_SIZE: f64 = 40.0;
6420
6421    // 'Drawer opens correctly with padding from MediaQuery (LTR)' .
6422    #[test]
6423    fn the_left_padding_widens_the_drawers_edge_drag_area() {
6424        test_widgets(|tester| {
6425            let key = GlobalKey::new();
6426            pump_app(tester, |_app| {
6427                text_drawer_scaffold(&key, "Scaffold Body").into_widget()
6428            });
6429            let scaffold_state = scaffold_state(tester, &key);
6430            assert!(!scaffold_state.is_drawer_open(&tester.cell.borrow()));
6431
6432            tester.drag_from(
6433                Offset::new(SIMULATED_NOTCH_SIZE + 15.0, 100.0),
6434                Offset::new(300.0, 0.0),
6435                1,
6436            );
6437            tester.pump_and_settle();
6438            assert!(!scaffold_state.is_drawer_open(&tester.cell.borrow()));
6439
6440            pump_app(tester, |_app| {
6441                MediaQuery::new(
6442                    MediaQueryData::new().padding(EdgeInsets::only(
6443                        SIMULATED_NOTCH_SIZE,
6444                        0.0,
6445                        0.0,
6446                        0.0,
6447                    )),
6448                    text_drawer_scaffold(&key, "Scaffold Body"),
6449                )
6450                .into_widget()
6451            });
6452            let scaffold_state = self::scaffold_state(tester, &key);
6453            assert!(!scaffold_state.is_drawer_open(&tester.cell.borrow()));
6454
6455            tester.drag_from(
6456                Offset::new(SIMULATED_NOTCH_SIZE + 15.0, 100.0),
6457                Offset::new(300.0, 0.0),
6458                2,
6459            );
6460            tester.pump_and_settle();
6461            assert!(scaffold_state.is_drawer_open(&tester.cell.borrow()));
6462        });
6463    }
6464
6465    // 'Drawer opens correctly with padding from MediaQuery (RTL)' .
6466    #[test]
6467    fn the_right_padding_widens_the_drawers_edge_drag_area_right_to_left() {
6468        test_widgets(|tester| {
6469            let key = GlobalKey::new();
6470            pump_app(tester, |_app| {
6471                text_drawer_scaffold(&key, "Scaffold Body").into_widget()
6472            });
6473            let scaffold_width = size_of(tester, &key).width();
6474            let scaffold_state = scaffold_state(tester, &key);
6475            assert!(!scaffold_state.is_drawer_open(&tester.cell.borrow()));
6476
6477            tester.drag_from(
6478                Offset::new(scaffold_width - SIMULATED_NOTCH_SIZE - 15.0, 100.0),
6479                Offset::new(-300.0, 0.0),
6480                1,
6481            );
6482            tester.pump_and_settle();
6483            assert!(!scaffold_state.is_drawer_open(&tester.cell.borrow()));
6484
6485            pump_app(tester, |_app| {
6486                MediaQuery::new(
6487                    MediaQueryData::new().padding(EdgeInsets::only(
6488                        0.0,
6489                        0.0,
6490                        SIMULATED_NOTCH_SIZE,
6491                        0.0,
6492                    )),
6493                    Directionality::new(
6494                        TextDirection::Rtl,
6495                        text_drawer_scaffold(&key, "Scaffold body"),
6496                    ),
6497                )
6498                .into_widget()
6499            });
6500            let scaffold_state = self::scaffold_state(tester, &key);
6501            assert!(!scaffold_state.is_drawer_open(&tester.cell.borrow()));
6502
6503            tester.drag_from(
6504                Offset::new(scaffold_width - SIMULATED_NOTCH_SIZE - 15.0, 100.0),
6505                Offset::new(-300.0, 0.0),
6506                2,
6507            );
6508            tester.pump_and_settle();
6509            assert!(scaffold_state.is_drawer_open(&tester.cell.borrow()));
6510        });
6511    }
6512
6513    // 'Drawer does not open with a drag gesture when it is disabled on mobile'.
6514    #[test]
6515    fn a_disabled_drag_gesture_does_not_open_the_drawer_but_still_closes_it_on_mobile() {
6516        for platform in [
6517            TargetPlatform::Android,
6518            TargetPlatform::Fuchsia,
6519            TargetPlatform::IOS,
6520        ] {
6521            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
6522                let key = GlobalKey::new();
6523                pump_app(tester, |_app| {
6524                    text_drawer_scaffold(&key, "Scaffold Body").into_widget()
6525                });
6526                let scaffold_state = scaffold_state(tester, &key);
6527                assert!(!scaffold_state.is_drawer_open(&tester.cell.borrow()));
6528
6529                // Test that we can open the drawer with a drag gesture when
6530                // `Scaffold.drawerEnableDragGesture` is true.
6531                tester.drag_from(Offset::new(0.0, 100.0), Offset::new(300.0, 0.0), 1);
6532                tester.pump_and_settle();
6533                assert!(
6534                    scaffold_state.is_drawer_open(&tester.cell.borrow()),
6535                    "{platform:?}"
6536                );
6537
6538                tester.drag_from(Offset::new(300.0, 100.0), Offset::new(-300.0, 0.0), 2);
6539                tester.pump_and_settle();
6540                assert!(
6541                    !scaffold_state.is_drawer_open(&tester.cell.borrow()),
6542                    "{platform:?}"
6543                );
6544
6545                pump_app(tester, |_app| {
6546                    text_drawer_scaffold(&key, "Scaffold body")
6547                        .drawer_enable_open_drag_gesture(false)
6548                        .into_widget()
6549                });
6550                let scaffold_state = self::scaffold_state(tester, &key);
6551                assert!(!scaffold_state.is_drawer_open(&tester.cell.borrow()));
6552
6553                // Test that we cannot open the drawer with a drag gesture when
6554                // `Scaffold.drawerEnableDragGesture` is false.
6555                tester.drag_from(Offset::new(0.0, 100.0), Offset::new(300.0, 0.0), 3);
6556                tester.pump_and_settle();
6557                assert!(
6558                    !scaffold_state.is_drawer_open(&tester.cell.borrow()),
6559                    "{platform:?}"
6560                );
6561
6562                // Test that we can close drawer with a drag gesture when
6563                // `Scaffold.drawerEnableDragGesture` is false.
6564                tap_first_icon_button(tester, 5);
6565                tester.pump_and_settle();
6566                assert!(
6567                    scaffold_state.is_drawer_open(&tester.cell.borrow()),
6568                    "{platform:?}"
6569                );
6570
6571                tester.drag_from(Offset::new(300.0, 100.0), Offset::new(-300.0, 0.0), 4);
6572                tester.pump_and_settle();
6573                assert!(
6574                    !scaffold_state.is_drawer_open(&tester.cell.borrow()),
6575                    "{platform:?}"
6576                );
6577            });
6578        }
6579    }
6580
6581    // 'Drawer does not open with a drag gesture on desktop'.
6582    #[test]
6583    fn the_drawer_does_not_follow_drags_on_desktop() {
6584        for platform in [
6585            TargetPlatform::Linux,
6586            TargetPlatform::MacOS,
6587            TargetPlatform::Windows,
6588        ] {
6589            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
6590                let key = GlobalKey::new();
6591                pump_app(tester, |_app| {
6592                    text_drawer_scaffold(&key, "Scaffold Body").into_widget()
6593                });
6594                let scaffold_state = scaffold_state(tester, &key);
6595                assert!(!scaffold_state.is_drawer_open(&tester.cell.borrow()));
6596
6597                // Test that we cannot open the drawer with a drag gesture.
6598                tester.drag_from(Offset::new(0.0, 100.0), Offset::new(300.0, 0.0), 1);
6599                tester.pump_and_settle();
6600                assert!(
6601                    !scaffold_state.is_drawer_open(&tester.cell.borrow()),
6602                    "{platform:?}"
6603                );
6604
6605                // Test that we can open the drawer with a tap gesture on drawer icon button.
6606                tap_first_icon_button(tester, 5);
6607                tester.pump_and_settle();
6608                assert!(
6609                    scaffold_state.is_drawer_open(&tester.cell.borrow()),
6610                    "{platform:?}"
6611                );
6612
6613                // Test that we cannot close the drawer with a drag gesture.
6614                tester.drag_from(Offset::new(300.0, 100.0), Offset::new(-300.0, 0.0), 2);
6615                tester.pump_and_settle();
6616                assert!(
6617                    scaffold_state.is_drawer_open(&tester.cell.borrow()),
6618                    "{platform:?}"
6619                );
6620
6621                // Test that we can close the drawer with a tap gesture in the body.
6622                tester.tap_at(Offset::new(500.0, 300.0), 3);
6623                tester.pump_and_settle();
6624                assert!(
6625                    !scaffold_state.is_drawer_open(&tester.cell.borrow()),
6626                    "{platform:?}"
6627                );
6628            });
6629        }
6630    }
6631
6632    // 'End drawer does not open with a drag gesture when it is disabled'.
6633    #[test]
6634    fn a_disabled_drag_gesture_does_not_open_the_end_drawer_but_still_closes_it() {
6635        test_widgets(|tester| {
6636            let key = GlobalKey::new();
6637            let end_drawer_scaffold = |key: &GlobalKey, body: &str| {
6638                Scaffold::new()
6639                    .key(key.clone().into())
6640                    .end_drawer(
6641                        crate::drawer::Drawer::new().child(waft_widgets::Text::new("Drawer")),
6642                    )
6643                    .body(waft_widgets::Text::new(body))
6644                    .app_bar(centered_title_app_bar())
6645            };
6646            let screen_width = WidgetTester::SIZE.width();
6647            pump_app(tester, |_app| {
6648                end_drawer_scaffold(&key, "Scaffold Body").into_widget()
6649            });
6650            let scaffold_state = scaffold_state(tester, &key);
6651            assert!(!scaffold_state.is_end_drawer_open(&tester.cell.borrow()));
6652
6653            // Test that we can open the end drawer with a drag gesture when
6654            // `Scaffold.endDrawerEnableDragGesture` is true.
6655            tester.drag_from(
6656                Offset::new(screen_width - 1.0, 100.0),
6657                Offset::new(-300.0, 0.0),
6658                1,
6659            );
6660            tester.pump_and_settle();
6661            assert!(scaffold_state.is_end_drawer_open(&tester.cell.borrow()));
6662
6663            tester.drag_from(
6664                Offset::new(screen_width - 300.0, 100.0),
6665                Offset::new(300.0, 0.0),
6666                2,
6667            );
6668            tester.pump_and_settle();
6669            assert!(!scaffold_state.is_end_drawer_open(&tester.cell.borrow()));
6670
6671            pump_app(tester, |_app| {
6672                end_drawer_scaffold(&key, "Scaffold body")
6673                    .end_drawer_enable_open_drag_gesture(false)
6674                    .into_widget()
6675            });
6676            let scaffold_state = self::scaffold_state(tester, &key);
6677            assert!(!scaffold_state.is_end_drawer_open(&tester.cell.borrow()));
6678
6679            // Test that we cannot open the end drawer with a drag gesture when
6680            // `Scaffold.endDrawerEnableDragGesture` is false.
6681            tester.drag_from(
6682                Offset::new(screen_width - 1.0, 100.0),
6683                Offset::new(-300.0, 0.0),
6684                3,
6685            );
6686            tester.pump_and_settle();
6687            assert!(!scaffold_state.is_end_drawer_open(&tester.cell.borrow()));
6688
6689            // Test that we can close the end drawer a with drag gesture when
6690            // `Scaffold.endDrawerEnableDragGesture` is false.
6691            tap_first_icon_button(tester, 5);
6692            tester.pump_and_settle();
6693            assert!(scaffold_state.is_end_drawer_open(&tester.cell.borrow()));
6694
6695            tester.drag_from(
6696                Offset::new(screen_width - 300.0, 100.0),
6697                Offset::new(300.0, 0.0),
6698                4,
6699            );
6700            tester.pump_and_settle();
6701            assert!(!scaffold_state.is_end_drawer_open(&tester.cell.borrow()));
6702        });
6703    }
6704
6705    /// Dart's `_GeometryListener`: listens to `Scaffold.geometryOf` and caches its value
6706    /// while painting, the only phase it may be read in.
6707    /// What a [`GeometryCachePainter`] last read, shared with the case.
6708    type GeometryCache = Rc<Cell<Option<ScaffoldGeometry>>>;
6709
6710    #[derive(Debug)]
6711    struct GeometryListener {
6712        cache: GeometryCache,
6713        num_notifications: Rc<Cell<usize>>,
6714    }
6715
6716    impl GeometryListener {
6717        fn new() -> (GeometryListener, GeometryCache, Rc<Cell<usize>>) {
6718            let cache = Rc::new(Cell::new(None));
6719            let num_notifications = Rc::new(Cell::new(0));
6720            (
6721                GeometryListener {
6722                    cache: Rc::clone(&cache),
6723                    num_notifications: Rc::clone(&num_notifications),
6724                },
6725                cache,
6726                num_notifications,
6727            )
6728        }
6729    }
6730
6731    impl StatefulWidget for GeometryListener {
6732        type State = GeometryListenerState;
6733
6734        fn create_state(&self) -> GeometryListenerState {
6735            let num_notifications = Rc::clone(&self.num_notifications);
6736            GeometryListenerState {
6737                state: StateData::new(),
6738                geometry_listenable: None,
6739                on_geometry_changed: Listener::new(move |_app| {
6740                    num_notifications.set(num_notifications.get() + 1)
6741                }),
6742            }
6743        }
6744    }
6745
6746    struct GeometryListenerState {
6747        state: StateData<GeometryListener>,
6748        geometry_listenable: Option<Ref<ScaffoldGeometryNotifier>>,
6749        on_geometry_changed: Listener,
6750    }
6751
6752    impl State for GeometryListenerState {
6753        type Widget = GeometryListener;
6754        waft_widgets::state_accessors!();
6755
6756        fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
6757            let context = self.context(app);
6758            let new_listenable = Scaffold::geometry_of(app, context);
6759            if app.get(self).geometry_listenable.as_ref() == Some(&new_listenable) {
6760                return;
6761            }
6762            let on_geometry_changed = app.get(self).on_geometry_changed.clone();
6763            if let Some(old) = app.get(self).geometry_listenable.clone() {
6764                old.remove_listener(app, &on_geometry_changed);
6765            }
6766            new_listenable.add_listener(app, on_geometry_changed);
6767            app.get_mut(self).geometry_listenable = Some(new_listenable);
6768        }
6769
6770        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
6771            let notifier = app
6772                .get(self)
6773                .geometry_listenable
6774                .clone()
6775                .expect("set by did_change_dependencies");
6776            CustomPaint::new()
6777                .painter(GeometryCachePainter {
6778                    notifier: notifier.clone(),
6779                    repaint: Rc::new(notifier),
6780                    cache: Rc::clone(&self.widget(app).cache),
6781                })
6782                .into_widget()
6783        }
6784    }
6785
6786    /// Dart's `_GeometryCachePainter`.
6787    struct GeometryCachePainter {
6788        notifier: Ref<ScaffoldGeometryNotifier>,
6789        repaint: Rc<dyn waft_foundation::Listenable>,
6790        cache: GeometryCache,
6791    }
6792
6793    impl waft_rendering::CustomPainter for GeometryCachePainter {
6794        fn repaint(&self) -> Option<&Rc<dyn waft_foundation::Listenable>> {
6795            Some(&self.repaint)
6796        }
6797
6798        fn paint(&self, app: &mut App, _canvas: &mut waft_embedder::Canvas, _size: Size) {
6799            self.cache.set(Some(self.notifier.value(app)));
6800        }
6801
6802        fn should_repaint(
6803            &self,
6804            _app: &App,
6805            _old_delegate: &dyn waft_rendering::CustomPainter,
6806        ) -> bool {
6807            true
6808        }
6809
6810        fn as_any(&self) -> &dyn Any {
6811            self
6812        }
6813    }
6814
6815    fn expanded_listener(listener: GeometryListener) -> WidgetRef {
6816        ConstrainedBox::new(BoxConstraints::expand(None, Some(80.0)))
6817            .child(listener)
6818            .into_widget()
6819    }
6820
6821    #[track_caller]
6822    fn assert_rect_through_transforms(actual: Rect, expected: Rect) {
6823        assert_through_transforms(actual.top_left(), expected.top_left());
6824        assert_through_transforms(actual.bottom_right(), expected.bottom_right());
6825    }
6826
6827    // 'ScaffoldGeometry bottomNavigationBar'.
6828    #[test]
6829    fn the_geometry_reports_the_bottom_navigation_bars_top() {
6830        test_widgets(|tester| {
6831            let key = GlobalKey::new();
6832            let (listener, cache, _) = GeometryListener::new();
6833            pump_app(tester, |_app| {
6834                Scaffold::new()
6835                    .body(Container::new())
6836                    .bottom_navigation_bar(
6837                        ConstrainedBox::new(BoxConstraints::expand(None, Some(80.0)))
6838                            .key(key.clone().into())
6839                            .child(listener),
6840                    )
6841                    .into_widget()
6842            });
6843            let navigation_height = size_of(tester, &key).height();
6844            let geometry = cache.get().expect("painted");
6845            assert_eq!(
6846                geometry.bottom_navigation_bar_top,
6847                Some(WidgetTester::SIZE.height() - navigation_height)
6848            );
6849        });
6850    }
6851
6852    // 'ScaffoldGeometry no bottomNavigationBar'.
6853    #[test]
6854    fn the_geometry_has_no_bottom_navigation_bar_top_without_a_bar() {
6855        test_widgets(|tester| {
6856            let (listener, cache, _) = GeometryListener::new();
6857            pump_app(tester, |_app| {
6858                Scaffold::new()
6859                    .body(expanded_listener(listener))
6860                    .into_widget()
6861            });
6862            let geometry = cache.get().expect("painted");
6863            assert_eq!(geometry.bottom_navigation_bar_top, None);
6864        });
6865    }
6866
6867    fn fab_with_listener(key: &GlobalKey, listener: GeometryListener) -> WidgetRef {
6868        FloatingActionButton::new(Some(Listener::new(|_| {})))
6869            .key(key.clone().into())
6870            .child(listener)
6871            .into_widget()
6872    }
6873
6874    // 'ScaffoldGeometry floatingActionButton'.
6875    #[test]
6876    fn the_geometry_reports_the_floating_action_buttons_area() {
6877        test_widgets(|tester| {
6878            let key = GlobalKey::new();
6879            let (listener, cache, _) = GeometryListener::new();
6880            pump_app(tester, |_app| {
6881                Scaffold::new()
6882                    .body(Container::new())
6883                    .floating_action_button(fab_with_listener(&key, listener))
6884                    .into_widget()
6885            });
6886            let fab_rect = rect_of(tester, &key);
6887            let geometry = cache.get().expect("painted");
6888            assert_rect_through_transforms(
6889                geometry.floating_action_button_area.expect("a fab area"),
6890                fab_rect,
6891            );
6892        });
6893    }
6894
6895    // 'ScaffoldGeometry no floatingActionButton'.
6896    #[test]
6897    fn the_geometry_has_no_floating_action_button_area_without_a_button() {
6898        test_widgets(|tester| {
6899            let (listener, cache, _) = GeometryListener::new();
6900            pump_app(tester, |_app| {
6901                Scaffold::new()
6902                    .body(expanded_listener(listener))
6903                    .into_widget()
6904            });
6905            let geometry = cache.get().expect("painted");
6906            assert_eq!(geometry.floating_action_button_area, None);
6907        });
6908    }
6909
6910    fn rotation_turns(tester: &WidgetTester) -> f64 {
6911        let rotation =
6912            tester.element(find::by_type::<waft_widgets::Animated<RotationTransition>>());
6913        let turns = tester.widget(
6914            rotation,
6915            |rotation: &waft_widgets::Animated<RotationTransition>| rotation.0.turns(),
6916        );
6917        turns.value(&tester.cell.borrow())
6918    }
6919
6920    // 'ScaffoldGeometry floatingActionButton entrance/exit animation'.
6921    #[test]
6922    fn the_geometry_scales_the_floating_action_button_area_while_it_enters() {
6923        test_widgets(|tester| {
6924            let key = GlobalKey::new();
6925            let (first_listener, _, _) = GeometryListener::new();
6926            pump_app(tester, |_app| {
6927                Scaffold::new()
6928                    .body(expanded_listener(first_listener))
6929                    .into_widget()
6930            });
6931
6932            let (listener, cache, _) = GeometryListener::new();
6933            pump_app(tester, |_app| {
6934                Scaffold::new()
6935                    .body(Container::new())
6936                    .floating_action_button(fab_with_listener(&key, listener))
6937                    .into_widget()
6938            });
6939
6940            tester.pump_by(Duration::from_millis(50));
6941
6942            let geometry = cache.get().expect("painted");
6943            let transitioning_fab_rect = geometry.floating_action_button_area.expect("an area");
6944
6945            let transitioning_rotation = rotation_turns(tester);
6946
6947            tester.pump_by(Duration::from_secs(3));
6948            let geometry = cache.get().expect("painted");
6949            let fab_rect = rect_of(tester, &key);
6950
6951            let completed_rotation = rotation_turns(tester);
6952
6953            assert!(transitioning_rotation < 1.0);
6954
6955            assert_eq!(completed_rotation, 1.0);
6956
6957            let area = geometry.floating_action_button_area.expect("an area");
6958            assert_rect_through_transforms(area, fab_rect);
6959
6960            assert_eq!(area.center(), transitioning_fab_rect.center());
6961
6962            assert!(area.width() > transitioning_fab_rect.width());
6963
6964            assert!(area.height() > transitioning_fab_rect.height());
6965        });
6966    }
6967
6968    // 'ScaffoldGeometry change notifications'.
6969    #[test]
6970    fn the_geometry_notifies_on_layout_and_while_the_button_animates() {
6971        test_widgets(|tester| {
6972            let key = GlobalKey::new();
6973            let (listener, _, num_notifications) = GeometryListener::new();
6974            let mut num_notifications_at_last_frame = 0;
6975            pump_app(tester, |_app| {
6976                Scaffold::new()
6977                    .body(expanded_listener(listener))
6978                    .into_widget()
6979            });
6980
6981            assert!(num_notifications.get() > num_notifications_at_last_frame);
6982            num_notifications_at_last_frame = num_notifications.get();
6983
6984            let (fab_listener, _, _) = GeometryListener::new();
6985            pump_app(tester, |_app| {
6986                Scaffold::new()
6987                    .body(Container::new())
6988                    .floating_action_button(fab_with_listener(&key, fab_listener))
6989                    .into_widget()
6990            });
6991
6992            assert!(num_notifications.get() > num_notifications_at_last_frame);
6993            num_notifications_at_last_frame = num_notifications.get();
6994
6995            tester.pump_by(Duration::from_millis(50));
6996
6997            assert!(num_notifications.get() > num_notifications_at_last_frame);
6998            num_notifications_at_last_frame = num_notifications.get();
6999
7000            tester.pump_by(Duration::from_secs(3));
7001
7002            assert!(num_notifications.get() > num_notifications_at_last_frame);
7003        });
7004    }
7005
7006    // 'Floating action entrance/exit animation'.
7007    #[test]
7008    fn a_new_floating_action_button_animates_in_and_the_first_one_does_not() {
7009        test_widgets(|tester| {
7010            let fab = |key: &str, label: &str| {
7011                FloatingActionButton::new(None)
7012                    .key(KeyRef::Local(Rc::new(ValueKey::new(key.to_string()))))
7013                    .child(waft_widgets::Text::new(label))
7014            };
7015            pump_app(tester, |_app| {
7016                Scaffold::new()
7017                    .floating_action_button(fab("one", "1"))
7018                    .into_widget()
7019            });
7020
7021            assert_eq!(transient_callback_count(tester), 0);
7022
7023            pump_app(tester, |_app| {
7024                Scaffold::new()
7025                    .floating_action_button(fab("two", "2"))
7026                    .into_widget()
7027            });
7028
7029            assert!(transient_callback_count(tester) > 0);
7030            tester.pump_widget(Container::new().into_widget());
7031            assert_eq!(transient_callback_count(tester), 0);
7032
7033            pump_app(tester, |_app| Scaffold::new().into_widget());
7034
7035            assert_eq!(transient_callback_count(tester), 0);
7036
7037            pump_app(tester, |_app| {
7038                Scaffold::new()
7039                    .floating_action_button(fab("one", "1"))
7040                    .into_widget()
7041            });
7042
7043            assert!(transient_callback_count(tester) > 0);
7044        });
7045    }
7046
7047    /// Dart's `find.byType(ElevatedButton)` tapped at its centre.
7048    fn tap_elevated_button(tester: &mut WidgetTester, label: &str, pointer: i64) {
7049        let text = *find::text(label)
7050            .evaluate(tester)
7051            .first()
7052            .expect("the button's label");
7053        let button = tester.ancestor_of_type::<ElevatedButton>(text);
7054        let at = center_of_element(tester, button);
7055        tester.tap_at(at, pointer);
7056    }
7057
7058    fn fab_top_left(tester: &WidgetTester) -> Offset {
7059        let fab = find::by_type::<FloatingActionButton>().evaluate(tester)[0];
7060        let render = tester.render_box_of(fab);
7061        let app = tester.cell.borrow();
7062        render.local_to_global(&app, Offset::ZERO, None)
7063    }
7064
7065    // 'FAB default entrance and exit animations'.
7066    #[test]
7067    fn the_floating_action_button_scales_in_and_out_by_default() {
7068        test_widgets(|tester| {
7069            let show_fab = Rc::new(Cell::new(false));
7070            pump_app(tester, |_app| {
7071                let show_fab = Rc::clone(&show_fab);
7072                StatefulBuilder::new(move |_app, _context, set_state| {
7073                    let toggle = {
7074                        let show_fab = Rc::clone(&show_fab);
7075                        Listener::new(move |app| {
7076                            let show_fab = Rc::clone(&show_fab);
7077                            set_state(app, &mut move |_app| show_fab.set(!show_fab.get()));
7078                        })
7079                    };
7080                    let mut scaffold = Scaffold::new().body(ElevatedButton::new(
7081                        Some(toggle),
7082                        Some(waft_widgets::Text::new("Toggle FAB")),
7083                    ));
7084                    if show_fab.get() {
7085                        scaffold = scaffold.floating_action_button(
7086                            FloatingActionButton::new(Some(Listener::new(|_| {})))
7087                                .child(waft_widgets::Icon::new(Some(crate::Icons::add()))),
7088                        );
7089                    }
7090                    scaffold.into_widget()
7091                })
7092                .into_widget()
7093            });
7094
7095            // FAB is not visible.
7096            assert!(
7097                find::by_type::<FloatingActionButton>()
7098                    .evaluate(tester)
7099                    .is_empty()
7100            );
7101
7102            // Tap the button to show the FAB.
7103            tap_elevated_button(tester, "Toggle FAB", 1);
7104            tester.pump();
7105            tester.pump_by(Duration::from_millis(100)); // Advance the animation by 100ms.
7106            // FAB is partially animated in.
7107            assert!(
7108                (fab_top_left(tester).dx() - 743.8).abs() < 0.1,
7109                "{}",
7110                fab_top_left(tester).dx()
7111            );
7112
7113            tester.pump_by(Duration::from_millis(100)); // Advance the animation by 100ms.
7114            // FAB is fully animated in.
7115            assert_through_transforms(
7116                fab_top_left(tester),
7117                Offset::new(728.0, fab_top_left(tester).dy()),
7118            );
7119
7120            // Tap the button to hide the FAB.
7121            tap_elevated_button(tester, "Toggle FAB", 2);
7122            tester.pump();
7123            tester.pump_by(Duration::from_millis(100)); // Advance the animation by 100ms.
7124            // FAB is partially animated out.
7125            assert!(
7126                (fab_top_left(tester).dx() - 747.1).abs() < 0.1,
7127                "{}",
7128                fab_top_left(tester).dx()
7129            );
7130
7131            tester.pump_by(Duration::from_millis(100)); // Advance the animation by 100ms.
7132            // FAB is fully animated out.
7133            assert_through_transforms(
7134                fab_top_left(tester),
7135                Offset::new(756.0, fab_top_left(tester).dy()),
7136            );
7137
7138            tester.pump_by(Duration::from_millis(50)); // Advance the animation by 50ms.
7139            // FAB is not visible.
7140            assert!(
7141                find::by_type::<FloatingActionButton>()
7142                    .evaluate(tester)
7143                    .is_empty()
7144            );
7145        });
7146    }
7147
7148    // 'FAB default entrance and exit animations can be disabled'.
7149    #[test]
7150    fn the_no_animation_animator_shows_hides_and_moves_the_button_at_once() {
7151        test_widgets(|tester| {
7152            let show_fab = Rc::new(Cell::new(false));
7153            let fab_location =
7154                Rc::new(RefCell::new(<dyn FloatingActionButtonLocation>::end_float()));
7155            pump_app(tester, |_app| {
7156                let show_fab = Rc::clone(&show_fab);
7157                let fab_location = Rc::clone(&fab_location);
7158                StatefulBuilder::new(move |_app, _context, set_state| {
7159                    let toggle = {
7160                        let show_fab = Rc::clone(&show_fab);
7161                        let set_state = Rc::clone(&set_state);
7162                        Listener::new(move |app| {
7163                            let show_fab = Rc::clone(&show_fab);
7164                            set_state(app, &mut move |_app| show_fab.set(!show_fab.get()));
7165                        })
7166                    };
7167                    let update_location = {
7168                        let fab_location = Rc::clone(&fab_location);
7169                        Listener::new(move |app| {
7170                            let fab_location = Rc::clone(&fab_location);
7171                            set_state(app, &mut move |_app| {
7172                                *fab_location.borrow_mut() =
7173                                    <dyn FloatingActionButtonLocation>::center_float();
7174                            });
7175                        })
7176                    };
7177                    let mut scaffold = Scaffold::new()
7178                        // Disable FAB animations.
7179                        .floating_action_button_animator(
7180                            <dyn FloatingActionButtonAnimator>::no_animation(),
7181                        )
7182                        .floating_action_button_location(Rc::clone(&fab_location.borrow()))
7183                        .body(
7184                            Column::new().children([
7185                                ElevatedButton::new(
7186                                    Some(toggle),
7187                                    Some(waft_widgets::Text::new("Toggle FAB")),
7188                                )
7189                                .into_widget(),
7190                                ElevatedButton::new(
7191                                    Some(update_location),
7192                                    Some(waft_widgets::Text::new("Update FAB Location")),
7193                                )
7194                                .into_widget(),
7195                            ]),
7196                        );
7197                    if show_fab.get() {
7198                        scaffold = scaffold.floating_action_button(
7199                            FloatingActionButton::new(Some(Listener::new(|_| {})))
7200                                .child(waft_widgets::Icon::new(Some(crate::Icons::add()))),
7201                        );
7202                    }
7203                    scaffold.into_widget()
7204                })
7205                .into_widget()
7206            });
7207
7208            // FAB is not visible.
7209            assert!(
7210                find::by_type::<FloatingActionButton>()
7211                    .evaluate(tester)
7212                    .is_empty()
7213            );
7214
7215            // Tap the button to show the FAB.
7216            tap_elevated_button(tester, "Toggle FAB", 1);
7217            tester.pump();
7218            // FAB is visible.
7219            assert_eq!(fab_top_left(tester).dx(), 728.0);
7220
7221            // Tap the button to hide the FAB.
7222            tap_elevated_button(tester, "Toggle FAB", 2);
7223            tester.pump();
7224            // FAB is not visible.
7225            assert!(
7226                find::by_type::<FloatingActionButton>()
7227                    .evaluate(tester)
7228                    .is_empty()
7229            );
7230
7231            // Tap the button to show the FAB.
7232            tap_elevated_button(tester, "Toggle FAB", 3);
7233            tester.pump();
7234            // FAB is visible.
7235            assert_eq!(fab_top_left(tester).dx(), 728.0);
7236
7237            // Tap the update location button.
7238            tap_elevated_button(tester, "Update FAB Location", 4);
7239            tester.pump();
7240
7241            // FAB is visible at the new location.
7242            assert_eq!(fab_top_left(tester).dx(), 372.0);
7243
7244            // Tap the button to hide the FAB.
7245            tap_elevated_button(tester, "Toggle FAB", 5);
7246            tester.pump();
7247            // FAB is not visible.
7248            assert!(
7249                find::by_type::<FloatingActionButton>()
7250                    .evaluate(tester)
7251                    .is_empty()
7252            );
7253        });
7254    }
7255
7256    // 'ScaffoldMessenger showSnackBar throws an intuitive error message if called during build'.
7257    #[test]
7258    #[should_panic(expected = "The showSnackBar() method cannot be called during build.\n")]
7259    fn show_snack_bar_during_build_explains_where_to_call_it_instead() {
7260        test_widgets(|tester| {
7261            pump_app(tester, |_app| {
7262                Scaffold::new()
7263                    .body(Builder::new(|app, context| {
7264                        ScaffoldMessenger::of(app, context).show_snack_bar(
7265                            app,
7266                            SnackBar::new(waft_widgets::Text::new("SnackBar")),
7267                            None,
7268                        );
7269                        SizedBox::shrink().into_widget()
7270                    }))
7271                    .into_widget()
7272            });
7273        });
7274    }
7275
7276    fn panic_message(panic: Box<dyn Any + Send>) -> String {
7277        panic
7278            .downcast_ref::<String>()
7279            .cloned()
7280            .or_else(|| panic.downcast_ref::<&str>().map(|text| text.to_string()))
7281            .unwrap_or_default()
7282    }
7283
7284    /// Runs `call` at the context of a `Builder` keyed `key`, catching its panic.
7285    fn panic_at(
7286        tester: &WidgetTester,
7287        key: &GlobalKey,
7288        call: impl FnOnce(&mut App, BuildContext),
7289    ) -> String {
7290        let mut app = tester.cell.borrow_mut();
7291        let context = key.current_context(&app).expect("a mounted builder");
7292        let outcome =
7293            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| call(&mut app, context)));
7294        panic_message(outcome.expect_err("the call panics"))
7295    }
7296
7297    fn keyed_builder(key: &GlobalKey) -> WidgetRef {
7298        Builder::new(|_app, _context| Container::new().into_widget())
7299            .key(key.clone().into())
7300            .into_widget()
7301    }
7302
7303    // 'Call to Scaffold.of() without context' (Dart calls it while building; here it is
7304    // called at the builder's context, which is where Dart's build runs it).
7305    #[test]
7306    fn scaffold_of_without_a_scaffold_explains_how_to_reach_one() {
7307        test_widgets(|tester| {
7308            let key = GlobalKey::new();
7309            pump_app(tester, |_app| keyed_builder(&key));
7310            let message = panic_at(tester, &key, |app, context| {
7311                Scaffold::of(app, context);
7312            });
7313            assert!(
7314                message.starts_with(
7315                    "Scaffold.of() called with a context that does not contain a Scaffold.\n\
7316                     No Scaffold ancestor could be found starting from the context that was \
7317                     passed to Scaffold.of(). This usually happens when the context provided is \
7318                     from the same StatefulWidget as that whose build function actually creates \
7319                     the Scaffold widget being sought.\n\
7320                     There are several ways to avoid this problem. The simplest is to use a \
7321                     Builder to get a context that is \"under\" the Scaffold. For an example of \
7322                     this, please see the documentation for Scaffold.of():\n  \
7323                     https://api.flutter.dev/flutter/material/Scaffold/of.html\n\
7324                     A more efficient solution is to split your build function into several \
7325                     widgets. This introduces a new context from which you can obtain the \
7326                     Scaffold. In this solution, you would have an outer widget that creates the \
7327                     Scaffold populated by instances of your new inner widgets, and then in these \
7328                     inner widgets you would use Scaffold.of().\n\
7329                     A less elegant but more expedient solution is assign a GlobalKey to the \
7330                     Scaffold, then use the key.currentState property to obtain the \
7331                     ScaffoldState rather than using the Scaffold.of() function.\n\
7332                     The context used was:\n"
7333                ),
7334                "{message}"
7335            );
7336            assert!(message.contains("Builder"), "{message}");
7337        });
7338    }
7339
7340    // 'Call to Scaffold.geometryOf() without context'.
7341    #[test]
7342    fn geometry_of_without_a_scaffold_explains_how_to_reach_one() {
7343        test_widgets(|tester| {
7344            let key = GlobalKey::new();
7345            pump_app(tester, |_app| keyed_builder(&key));
7346            let message = panic_at(tester, &key, |app, context| {
7347                Scaffold::geometry_of(app, context);
7348            });
7349            assert!(
7350                message.starts_with(
7351                    "Scaffold.geometryOf() called with a context that does not contain a \
7352                     Scaffold.\n\
7353                     This usually happens when the context provided is from the same \
7354                     StatefulWidget as that whose build function actually creates the Scaffold \
7355                     widget being sought.\n\
7356                     There are several ways to avoid this problem. The simplest is to use a \
7357                     Builder to get a context that is \"under\" the Scaffold. For an example of \
7358                     this, please see the documentation for Scaffold.of():\n  \
7359                     https://api.flutter.dev/flutter/material/Scaffold/of.html\n\
7360                     A more efficient solution is to split your build function into several \
7361                     widgets. This introduces a new context from which you can obtain the \
7362                     Scaffold. In this solution, you would have an outer widget that creates the \
7363                     Scaffold populated by instances of your new inner widgets, and then in these \
7364                     inner widgets you would use Scaffold.geometryOf().\n\
7365                     The context used was:\n"
7366                ),
7367                "{message}"
7368            );
7369            assert!(message.contains("Builder"), "{message}");
7370        });
7371    }
7372
7373    // 'FloatingActionButton always keeps the same position regardless of extendBodyBehindAppBar'.
7374    #[test]
7375    fn the_floating_action_button_keeps_its_place_when_the_body_extends_behind_the_app_bar() {
7376        test_widgets(|tester| {
7377            let fab_center_y = |tester: &mut WidgetTester, extend_body_behind_app_bar: bool| {
7378                pump_app(tester, |_app| {
7379                    Scaffold::new()
7380                        .app_bar(PreferredSizeWidgetRef::new(AppBar::new()))
7381                        .floating_action_button(
7382                            FloatingActionButton::new(Some(Listener::new(|_| {})))
7383                                .child(waft_widgets::Icon::new(Some(crate::icons::Icons::add()))),
7384                        )
7385                        .floating_action_button_location(
7386                            <dyn FloatingActionButtonLocation>::end_top(),
7387                        )
7388                        .extend_body_behind_app_bar(extend_body_behind_app_bar)
7389                        .into_widget()
7390                });
7391                let fab = find::by_type::<FloatingActionButton>().evaluate(tester)[0];
7392                let render = tester.render_box_of(fab);
7393                tester.global_rect(render).center().dy()
7394            };
7395
7396            let default_offset_y = fab_center_y(tester, false);
7397            let extended_body_offset_y = fab_center_y(tester, true);
7398
7399            assert_eq!(default_offset_y, extended_body_offset_y);
7400        });
7401    }
7402
7403    /// `Directionality(MediaQuery(Scaffold(body: Builder(builder: (context) =>
7404    /// GestureDetector(key: tapTarget, onTap: on_tap(context), behavior: opaque, child:
7405    /// SizedBox(100, 100))))))`.
7406    fn tap_target_scaffold(
7407        tap_target: &GlobalKey,
7408        with_media_query: bool,
7409        on_tap: impl Fn(&mut App, BuildContext) + 'static,
7410    ) -> WidgetRef {
7411        let on_tap = Rc::new(on_tap);
7412        let tap_target = tap_target.clone();
7413        let scaffold = Scaffold::new().body(Builder::new(move |_app, context| {
7414            let on_tap = Rc::clone(&on_tap);
7415            waft_widgets::GestureDetector::new()
7416                .key(tap_target.clone().into())
7417                .on_tap(Listener::new(move |app| on_tap(app, context)))
7418                .behavior(HitTestBehavior::Opaque)
7419                .child(SizedBox::new().width(100.0).height(100.0))
7420                .into_widget()
7421        }));
7422        if with_media_query {
7423            directional(TextDirection::Ltr, MediaQueryData::new(), scaffold)
7424        } else {
7425            Directionality::new(TextDirection::Ltr, scaffold).into_widget()
7426        }
7427    }
7428
7429    // 'ScaffoldMessenger.maybeOf can return null if not found'.
7430    #[test]
7431    fn scaffold_messenger_maybe_of_is_none_without_a_messenger() {
7432        test_widgets(|tester| {
7433            let tap_target = GlobalKey::new();
7434            let scaffold_messenger = Rc::new(Cell::new(Some(None)));
7435            tester.pump_widget(tap_target_scaffold(&tap_target, true, {
7436                let scaffold_messenger = Rc::clone(&scaffold_messenger);
7437                move |app, context| {
7438                    scaffold_messenger.set(Some(ScaffoldMessenger::maybe_of(app, context)));
7439                }
7440            }));
7441            let at = tester.get_center(&tap_target);
7442            tester.tap_at(at, 1);
7443            tester.pump();
7444            assert_eq!(scaffold_messenger.get(), Some(None));
7445        });
7446    }
7447
7448    /// `TextButton(onPressed:, child: Text(label))`.
7449    fn text_button(label: &'static str, on_pressed: impl Fn(&mut App) + 'static) -> WidgetRef {
7450        TextButton::new(
7451            Some(Listener::new(on_pressed)),
7452            Some(waft_widgets::Text::new(label)),
7453        )
7454        .into_widget()
7455    }
7456
7457    /// Dart's `tester.tap(find.text(label))`, which skips offstage widgets.
7458    fn tap_onstage_text(tester: &mut WidgetTester, label: &str, pointer: i64) {
7459        let found = find::text(label).evaluate(tester);
7460        assert_eq!(found.len(), 1, "one onstage {label:?}");
7461        let at = tester.get_rect(found[0]).center();
7462        tester.tap_at(at, pointer);
7463    }
7464
7465    // 'ScaffoldMessenger checks for nesting when a new Scaffold is registered'. A
7466    // `PageRouteBuilder` stands in for the `MaterialPageRoute` Dart pushes, which is not ported.
7467    #[test]
7468    fn the_messenger_checks_for_nesting_when_a_new_scaffold_registers() {
7469        // Regression test for https://github.com/flutter/flutter/issues/77251
7470        test_widgets(|tester| {
7471            const SNACK_BAR_CONTENT: &str = "SnackBar Content";
7472            pump_app(tester, |_app| {
7473                Builder::new(|_app, context| {
7474                    Scaffold::new()
7475                        .body(Scaffold::new().body(text_button("Push route", move |app| {
7476                            let page_builder: waft_widgets::RoutePageBuilder =
7477                                Rc::new(|_app, context, _, _| {
7478                                    Scaffold::new()
7479                                        .body(Column::new().children([
7480                                            text_button("Show SnackBar", move |app| {
7481                                                let snack_bar = SnackBar::new(
7482                                                    waft_widgets::Text::new(SNACK_BAR_CONTENT),
7483                                                )
7484                                                .behavior(SnackBarBehavior::Floating);
7485                                                ScaffoldMessenger::of(app, context)
7486                                                    .show_snack_bar(app, snack_bar, None);
7487                                            }),
7488                                            text_button("Pop route", move |app| {
7489                                                waft_widgets::Navigator::pop(app, context, None);
7490                                            }),
7491                                        ]))
7492                                        .into_widget()
7493                                });
7494                            let route = waft_widgets::PageRouteBuilder::new(app, page_builder);
7495                            drop(waft_widgets::Navigator::push(app, context, route.erase()));
7496                        })))
7497                        .into_widget()
7498                })
7499                .into_widget()
7500            });
7501
7502            let snack_bars =
7503                |tester: &WidgetTester| find::text(SNACK_BAR_CONTENT).evaluate(tester).len();
7504            assert_eq!(snack_bars(tester), 0);
7505            tap_onstage_text(tester, "Push route", 1);
7506            tester.pump_and_settle();
7507            assert_eq!(snack_bars(tester), 0);
7508            expect(tester, &find::text("Pop route"), finds_one_widget());
7509
7510            // Show SnackBar on second page
7511            tap_onstage_text(tester, "Show SnackBar", 2);
7512            tester.pump();
7513            assert_eq!(snack_bars(tester), 1);
7514            // Pop the second page, the SnackBar completes a hero animation to the next route.
7515            // If we have not handled the nested Scaffolds properly, this will throw an
7516            // exception as duplicate SnackBars on the first route would have a common hero tag.
7517            tap_onstage_text(tester, "Pop route", 3);
7518            tester.pump();
7519            // There are SnackBars two during the execution of the hero animation.
7520            assert_eq!(snack_bars(tester), 2);
7521            tester.pump_and_settle();
7522            assert_eq!(snack_bars(tester), 1);
7523            // Allow the SnackBar to animate out
7524            tester.pump_by(Duration::from_secs(4));
7525            tester.pump_and_settle();
7526            assert_eq!(snack_bars(tester), 0);
7527        });
7528    }
7529
7530    // 'ScaffoldMessenger.of will assert if not found'.
7531    #[test]
7532    fn scaffold_messenger_of_asserts_without_a_messenger() {
7533        test_widgets(|tester| {
7534            let tap_target = GlobalKey::new();
7535            tester.pump_widget(tap_target_scaffold(&tap_target, false, |app, context| {
7536                ScaffoldMessenger::of(app, context);
7537            }));
7538            let at = tester.get_center(&tap_target);
7539            let outcome =
7540                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| tester.tap_at(at, 1)));
7541            let message = panic_message(outcome.expect_err("ScaffoldMessenger.of panics"));
7542            assert!(
7543                message.starts_with("No ScaffoldMessenger widget found.\n"),
7544                "{message}"
7545            );
7546            // Dart's `runtimeType` is the widget's `Debug` here, as in debug_check_has_material;
7547            // the missing-ancestor description waits (debug.rs's Deferred line).
7548            assert!(
7549                message.contains("\nBuilder")
7550                    && message.contains(" widgets require a ScaffoldMessenger widget ancestor.\n"),
7551                "{message}"
7552            );
7553            assert!(
7554                message.ends_with(
7555                    "Typically, the ScaffoldMessenger widget is introduced by the MaterialApp at \
7556                     the top of your application widget tree."
7557                ),
7558                "{message}"
7559            );
7560        });
7561    }
7562
7563    // 'Default ScaffoldMessenger can access ambient theme'.
7564    #[test]
7565    fn the_default_scaffold_messenger_sees_the_apps_theme() {
7566        test_widgets(|tester| {
7567            let (theme, color_scheme) = {
7568                let app = tester.cell.borrow();
7569                let color_scheme =
7570                    crate::ColorScheme::from_seed(Colors::DEEP_PURPLE.primary()).build();
7571                let theme = ThemeData::builder()
7572                    .color_scheme(color_scheme.clone())
7573                    .visual_density(crate::VisualDensity::COMFORTABLE)
7574                    .build(&app);
7575                (theme, color_scheme)
7576            };
7577            tester.pump_widget(material_app(theme, SizedBox::shrink().into_widget()));
7578
7579            let messenger = find::by_type::<ScaffoldMessenger>().evaluate(tester)[0];
7580            let mut app = tester.cell.borrow_mut();
7581            let messenger_theme = Theme::of(&mut app, messenger);
7582            assert!(messenger_theme.color_scheme == color_scheme);
7583            assert_eq!(
7584                messenger_theme.visual_density,
7585                crate::VisualDensity::COMFORTABLE
7586            );
7587        });
7588    }
7589
7590    /// `MaterialApp(home: Scaffold(body: Builder(builder: (context) => ElevatedButton(
7591    /// onPressed: show the snack bar, child: Text('Show SnackBar')))))`.
7592    fn pump_snack_bar_app(tester: &mut WidgetTester, style: Option<AnimationStyle>) {
7593        pump_app(tester, move |_app| {
7594            Scaffold::new()
7595                .body(Builder::new(move |_app, context| {
7596                    let style = style.clone();
7597                    ElevatedButton::new(
7598                        Some(Listener::new(move |app| {
7599                            ScaffoldMessenger::of(app, context).show_snack_bar(
7600                                app,
7601                                SnackBar::new(waft_widgets::Text::new("I am a snack bar."))
7602                                    .show_close_icon(true),
7603                                style.clone(),
7604                            );
7605                        })),
7606                        Some(waft_widgets::Text::new("Show SnackBar")),
7607                    )
7608                    .into_widget()
7609                }))
7610                .into_widget()
7611        });
7612    }
7613
7614    fn snack_bar_text_top(tester: &WidgetTester) -> f64 {
7615        tester.get_rect(find::text("I am a snack bar.")).top
7616    }
7617
7618    #[track_caller]
7619    fn assert_close_to(actual: f64, expected: f64, epsilon: f64) {
7620        assert!(
7621            (actual - expected).abs() <= epsilon,
7622            "{actual} is not {expected}"
7623        );
7624    }
7625
7626    fn tap_close_icon(tester: &mut WidgetTester, pointer: i64) {
7627        let icon_button = find::by_type::<crate::IconButton>().evaluate(tester)[0];
7628        let at = center_of_element(tester, icon_button);
7629        tester.tap_at(at, pointer);
7630    }
7631
7632    // 'ScaffoldMessenger showSnackBar default animation'.
7633    #[test]
7634    fn the_snack_bar_slides_in_and_out_in_250_milliseconds_by_default() {
7635        test_widgets(|tester| {
7636            pump_snack_bar_app(tester, None);
7637
7638            // Tap the button to show the SnackBar.
7639            tap_elevated_button(tester, "Show SnackBar", 1);
7640            tester.pump();
7641            tester.pump_by(Duration::from_millis(125)); // Advance the animation by 125ms.
7642
7643            // The SnackBar is partially visible.
7644            assert_close_to(snack_bar_text_top(tester), 576.7, 0.1);
7645
7646            tester.pump_by(Duration::from_millis(125)); // Advance the animation by 125ms.
7647
7648            // The SnackBar is fully visible.
7649            assert_close_to(snack_bar_text_top(tester), 566.0, 0.1);
7650
7651            // Tap the close button to dismiss the SnackBar.
7652            tap_close_icon(tester, 2);
7653            tester.pump();
7654            tester.pump_by(Duration::from_millis(125)); // Advance the animation by 125ms.
7655
7656            // The SnackBar is partially visible.
7657            assert_close_to(snack_bar_text_top(tester), 576.7, 0.1);
7658
7659            tester.pump_by(Duration::from_millis(125)); // Advance the animation by 125ms.
7660
7661            // The SnackBar is dismissed.
7662            assert_close_to(snack_bar_text_top(tester), 614.0, 0.1);
7663        });
7664    }
7665
7666    // 'ScaffoldMessenger showSnackBar animation can be customized'.
7667    #[test]
7668    fn the_snack_bar_animation_style_sets_its_durations() {
7669        test_widgets(|tester| {
7670            pump_snack_bar_app(
7671                tester,
7672                Some(AnimationStyle::new(
7673                    None,
7674                    Some(Duration::from_millis(1200)),
7675                    None,
7676                    Some(Duration::from_millis(600)),
7677                )),
7678            );
7679
7680            // Tap the button to show the SnackBar.
7681            tap_elevated_button(tester, "Show SnackBar", 1);
7682            tester.pump();
7683            tester.pump_by(Duration::from_millis(300)); // Advance the animation by 300ms.
7684
7685            // The SnackBar is partially visible.
7686            assert_close_to(snack_bar_text_top(tester), 602.6, 0.1);
7687
7688            tester.pump_by(Duration::from_millis(300)); // Advance the animation by 300ms.
7689
7690            // The SnackBar is partially visible.
7691            assert_close_to(snack_bar_text_top(tester), 576.7, 0.1);
7692
7693            tester.pump_by(Duration::from_millis(600)); // Advance the animation by 600ms.
7694
7695            // The SnackBar is fully visible.
7696            assert_close_to(snack_bar_text_top(tester), 566.0, 0.1);
7697
7698            // Tap the close button to dismiss the SnackBar.
7699            tap_close_icon(tester, 2);
7700            tester.pump();
7701            tester.pump_by(Duration::from_millis(300)); // Advance the animation by 300ns.
7702
7703            // The SnackBar is partially visible.
7704            assert_close_to(snack_bar_text_top(tester), 576.7, 0.1);
7705
7706            tester.pump_by(Duration::from_millis(300)); // Advance the animation by 300ms.
7707
7708            // The SnackBar is dismissed.
7709            assert_close_to(snack_bar_text_top(tester), 614.0, 0.1);
7710        });
7711    }
7712
7713    // 'Updated snackBarAnimationStyle updates snack bar animation'.
7714    #[test]
7715    fn a_new_snack_bar_animation_style_replaces_the_old_durations() {
7716        test_widgets(|tester| {
7717            // Test custom animation style.
7718            pump_snack_bar_app(
7719                tester,
7720                Some(AnimationStyle::new(
7721                    None,
7722                    Some(Duration::from_millis(800)),
7723                    None,
7724                    Some(Duration::from_millis(400)),
7725                )),
7726            );
7727
7728            // Tap the button to show the SnackBar.
7729            tap_elevated_button(tester, "Show SnackBar", 1);
7730            tester.pump();
7731            tester.pump_by(Duration::from_millis(400)); // Advance the animation by 400ms.
7732
7733            // The SnackBar is partially visible.
7734            assert_close_to(snack_bar_text_top(tester), 576.7, 0.1);
7735
7736            tester.pump_by(Duration::from_millis(400)); // Advance the animation by 400ms.
7737
7738            // The SnackBar is fully visible.
7739            assert_close_to(snack_bar_text_top(tester), 566.0, 0.1);
7740
7741            // Tap the close button to dismiss the SnackBar.
7742            tap_close_icon(tester, 2);
7743            tester.pump();
7744            tester.pump_by(Duration::from_millis(400)); // Advance the animation by 400ms.
7745
7746            // The SnackBar is dismissed.
7747            assert_close_to(snack_bar_text_top(tester), 614.0, 0.1);
7748
7749            // Test no animation style.
7750            pump_snack_bar_app(tester, Some(AnimationStyle::NO_ANIMATION));
7751            tester.pump_and_settle();
7752
7753            // Tap the button to show the SnackBar.
7754            tap_elevated_button(tester, "Show SnackBar", 3);
7755            tester.pump();
7756
7757            // The SnackBar is fully visible.
7758            assert_close_to(snack_bar_text_top(tester), 566.0, 0.1);
7759
7760            // Tap the close button to dismiss the SnackBar.
7761            tap_close_icon(tester, 4);
7762            tester.pump();
7763
7764            // The SnackBar is dismissed.
7765            assert!(find::text("I am a snack bar.").evaluate(tester).is_empty());
7766        });
7767    }
7768
7769    // 'snackBarAnimationStyle with only reverseDuration uses default forward duration'.
7770    #[test]
7771    fn a_snack_bar_animation_style_with_only_a_reverse_duration_keeps_the_default_forward_one() {
7772        test_widgets(|tester| {
7773            // Test custom animation style with only reverseDuration.
7774            pump_snack_bar_app(
7775                tester,
7776                Some(AnimationStyle::new(
7777                    None,
7778                    None,
7779                    None,
7780                    Some(Duration::from_millis(400)),
7781                )),
7782            );
7783
7784            // Tap the button to show the SnackBar.
7785            tap_elevated_button(tester, "Show SnackBar", 1);
7786            tester.pump();
7787            // Advance the animation by 1/2 of the default forward duration.
7788            tester.pump_by(Duration::from_millis(125));
7789
7790            // The SnackBar is partially visible.
7791            assert_close_to(snack_bar_text_top(tester), 576.7, 0.1);
7792
7793            // Advance the animation by 1/2 of the default forward duration.
7794            tester.pump_by(Duration::from_millis(125)); // Advance the animation by 125ms.
7795
7796            // The SnackBar is fully visible.
7797            assert_close_to(snack_bar_text_top(tester), 566.0, 0.1);
7798
7799            // Tap the close button to dismiss the SnackBar.
7800            tap_close_icon(tester, 2);
7801            tester.pump();
7802            // Advance the animation by 1/2 of the reverse duration.
7803            tester.pump_by(Duration::from_millis(200));
7804
7805            // The SnackBar is partially visible.
7806            assert_close_to(snack_bar_text_top(tester), 576.7, 0.1);
7807
7808            // Advance the animation by 1/2 of the reverse duration.
7809            tester.pump_by(Duration::from_millis(200)); // Advance the animation by 200ms.
7810
7811            // The SnackBar is dismissed.
7812            assert_close_to(snack_bar_text_top(tester), 614.0, 0.1);
7813        });
7814    }
7815
7816    fn show_sheet(
7817        app: &mut App,
7818        scaffold: Handle<ScaffoldState>,
7819        builder: impl Fn(&mut App, BuildContext) -> WidgetRef + 'static,
7820        sheet_animation_style: Option<AnimationStyle>,
7821    ) -> Rc<PersistentBottomSheetController> {
7822        scaffold.show_bottom_sheet(
7823            app,
7824            Rc::new(builder),
7825            None,
7826            None,
7827            None,
7828            None,
7829            None,
7830            None,
7831            None,
7832            None,
7833            sheet_animation_style,
7834        )
7835    }
7836
7837    // 'showBottomSheet() while Scaffold has bottom sheet'.
7838    #[test]
7839    fn show_bottom_sheet_while_the_scaffold_has_a_bottom_sheet_asserts() {
7840        test_widgets(|tester| {
7841            let key = GlobalKey::new();
7842            pump_app(tester, |_app| {
7843                Scaffold::new()
7844                    .key(key.clone().into())
7845                    .body(Center::new().child(Container::new()))
7846                    .bottom_sheet(waft_widgets::Text::new("Bottom sheet"))
7847                    .into_widget()
7848            });
7849            let scaffold = scaffold_state(tester, &key);
7850            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
7851                show_sheet(
7852                    &mut tester.cell.borrow_mut(),
7853                    scaffold,
7854                    |_app, _context| Container::new().into_widget(),
7855                    None,
7856                );
7857            }));
7858            let message = panic_message(outcome.expect_err("showBottomSheet asserts"));
7859            assert_eq!(
7860                message,
7861                "Scaffold.bottomSheet cannot be specified while a bottom sheet displayed with \
7862                 showBottomSheet() is still visible.\n\
7863                 Rebuild the Scaffold with a null bottomSheet before calling showBottomSheet()."
7864            );
7865        });
7866    }
7867
7868    // 'didUpdate bottomSheet while a previous bottom sheet is still displayed'.
7869    #[test]
7870    #[should_panic(
7871        expected = "Scaffold.bottomSheet cannot be specified while a bottom sheet displayed with showBottomSheet() is still visible.\nUse the PersistentBottomSheetController returned by showBottomSheet() to close the old bottom sheet before creating a Scaffold with a (non null) bottomSheet."
7872    )]
7873    fn giving_the_scaffold_a_bottom_sheet_while_a_shown_one_is_visible_asserts() {
7874        test_widgets(|tester| {
7875            let key = GlobalKey::new();
7876            let button_key = GlobalKey::new();
7877            let state = Rc::new(Cell::new(0));
7878            pump_app(tester, |_app| {
7879                let state = Rc::clone(&state);
7880                let (key, button_key) = (key.clone(), button_key.clone());
7881                StatefulBuilder::new(move |_app, _context, set_state| {
7882                    let state_on_press = Rc::clone(&state);
7883                    let mut scaffold = Scaffold::new()
7884                        .key(key.clone().into())
7885                        .body(Container::new())
7886                        .floating_action_button(
7887                            FloatingActionButton::new(Some(Listener::new(move |app| {
7888                                state_on_press.set(state_on_press.get() + 1);
7889                                set_state(app, &mut |_app| {});
7890                            })))
7891                            .key(button_key.clone().into()),
7892                        );
7893                    if state.get() != 0 {
7894                        scaffold = scaffold.bottom_sheet(SizedBox::new());
7895                    }
7896                    scaffold.into_widget()
7897                })
7898                .into_widget()
7899            });
7900            let scaffold = scaffold_state(tester, &key);
7901            show_sheet(
7902                &mut tester.cell.borrow_mut(),
7903                scaffold,
7904                |_app, _context| Container::new().into_widget(),
7905                None,
7906            );
7907            let at = tester.get_center(&button_key);
7908            tester.tap_at(at, 1);
7909            // Dart: `expect(tester.takeException(), isAssertionError)`. The assertion unwinds out
7910            // of the pump, where `test_widgets` re-raises it.
7911            tester.pump();
7912        });
7913    }
7914
7915    /// `Scaffold(body: Builder(builder: (context) => GestureDetector(onTap: () =>
7916    /// Scaffold.of(context).showBottomSheet(..), child: Text('X'))))` with Dart's sheet: a
7917    /// `ColoredBox` keyed `sheet_key` filling the sheet, around a `FilledButton` that pops.
7918    fn pump_bottom_sheet_app(
7919        tester: &mut WidgetTester,
7920        sheet_key: &GlobalKey,
7921        sheet_animation_style: Option<AnimationStyle>,
7922    ) {
7923        let sheet_key = sheet_key.clone();
7924        pump_app(tester, move |_app| {
7925            Scaffold::new()
7926                .body(Builder::new(move |_app, context| {
7927                    let sheet_key = sheet_key.clone();
7928                    let sheet_animation_style = sheet_animation_style.clone();
7929                    waft_widgets::GestureDetector::new()
7930                        .on_tap(Listener::new(move |app| {
7931                            let sheet_key = sheet_key.clone();
7932                            let scaffold = Scaffold::of(app, context);
7933                            show_sheet(
7934                                app,
7935                                scaffold,
7936                                move |app, context| {
7937                                    let primary = Theme::of(app, context).color_scheme.primary();
7938                                    SizedBox::expand()
7939                                        .child(
7940                                            ColoredBox::new(primary)
7941                                                .key(sheet_key.clone().into())
7942                                                .child(crate::FilledButton::new(
7943                                                    Some(Listener::new(move |app| {
7944                                                        waft_widgets::Navigator::pop(
7945                                                            app, context, None,
7946                                                        )
7947                                                    })),
7948                                                    Some(waft_widgets::Text::new("Close")),
7949                                                )),
7950                                        )
7951                                        .into_widget()
7952                                },
7953                                sheet_animation_style.clone(),
7954                            );
7955                        }))
7956                        .child(waft_widgets::Text::new("X"))
7957                        .into_widget()
7958                }))
7959                .into_widget()
7960        });
7961    }
7962
7963    // 'Scaffold showBottomSheet default animation'.
7964    #[test]
7965    fn show_bottom_sheet_animates_in_250_and_out_200_milliseconds_by_default() {
7966        test_widgets(|tester| {
7967            let sheet_key = GlobalKey::new();
7968            pump_bottom_sheet_app(tester, &sheet_key, None);
7969
7970            // Tap the 'X' to show the bottom sheet.
7971            tester.tap(find::text("X"));
7972            tester.pump();
7973            // Advance the animation by 1/2 of the default forward duration.
7974            tester.pump_by(Duration::from_millis(125));
7975
7976            // The bottom sheet is partially visible.
7977            assert_close_to(rect_of(tester, &sheet_key).top, 134.6, 0.1);
7978
7979            // Advance the animation by 1/2 of the default forward duration.
7980            tester.pump_by(Duration::from_millis(125));
7981
7982            // The bottom sheet is fully visible.
7983            assert_eq!(rect_of(tester, &sheet_key).top, 0.0);
7984
7985            // Dismiss the bottom sheet.
7986            tester.tap(find::text("Close"));
7987            tester.pump();
7988            // Advance the animation by 1/2 of the default reverse duration.
7989            tester.pump_by(Duration::from_millis(100));
7990
7991            // The bottom sheet is partially visible.
7992            assert_close_to(rect_of(tester, &sheet_key).top, 134.6, 0.1);
7993
7994            // Advance the animation by 1/2 of the default reverse duration.
7995            tester.pump_by(Duration::from_millis(100));
7996
7997            // The bottom sheet is dismissed.
7998            assert_eq!(rect_of(tester, &sheet_key).top, 600.0);
7999        });
8000    }
8001
8002    /// Not a Dart case: what Flutter's leak tracking checks, that showing and closing a
8003    /// bottom sheet leaves nothing behind. The sheet's callbacks name the sheet itself, a ring
8004    /// Dart's collector frees.
8005    #[test]
8006    fn showing_and_closing_a_bottom_sheet_leaves_nothing_behind() {
8007        test_widgets(|tester| {
8008            let sheet_key = GlobalKey::new();
8009            pump_bottom_sheet_app(tester, &sheet_key, None);
8010            tester.assert_leaves_nothing_behind(|tester| {
8011                tester.tap(find::text("X"));
8012                tester.pump_and_settle();
8013                tester.tap(find::text("Close"));
8014                tester.pump_and_settle();
8015                assert!(sheet_key.current_context(&tester.cell.borrow()).is_none());
8016            });
8017        });
8018    }
8019
8020    // 'Scaffold showBottomSheet animation can be customized'.
8021    #[test]
8022    fn the_sheet_animation_style_sets_show_bottom_sheets_durations() {
8023        test_widgets(|tester| {
8024            let sheet_key = GlobalKey::new();
8025            // Test custom animation style.
8026            pump_bottom_sheet_app(
8027                tester,
8028                &sheet_key,
8029                Some(AnimationStyle::new(
8030                    None,
8031                    Some(Duration::from_millis(800)),
8032                    None,
8033                    Some(Duration::from_millis(400)),
8034                )),
8035            );
8036            tester.tap(find::text("X"));
8037            tester.pump();
8038            // Advance the animation by 1/2 of the custom forward duration.
8039            tester.pump_by(Duration::from_millis(400));
8040
8041            // The bottom sheet is partially visible.
8042            assert_close_to(rect_of(tester, &sheet_key).top, 134.6, 0.1);
8043
8044            // Advance the animation by 1/2 of the custom forward duration.
8045            tester.pump_by(Duration::from_millis(400));
8046
8047            // The bottom sheet is fully visible.
8048            assert_eq!(rect_of(tester, &sheet_key).top, 0.0);
8049
8050            // Dismiss the bottom sheet.
8051            tester.tap(find::text("Close"));
8052            tester.pump();
8053            // Advance the animation by 1/2 of the custom reverse duration.
8054            tester.pump_by(Duration::from_millis(200));
8055
8056            // The bottom sheet is partially visible.
8057            assert_close_to(rect_of(tester, &sheet_key).top, 134.6, 0.1);
8058
8059            // Advance the animation by 1/2 of the custom reverse duration.
8060            tester.pump_by(Duration::from_millis(200));
8061
8062            // The bottom sheet is dismissed.
8063            assert_eq!(rect_of(tester, &sheet_key).top, 600.0);
8064
8065            // Test no animation style.
8066            pump_bottom_sheet_app(tester, &sheet_key, Some(AnimationStyle::NO_ANIMATION));
8067            tester.pump_and_settle();
8068            tester.tap(find::text("X"));
8069            tester.pump();
8070
8071            // The bottom sheet is fully visible.
8072            assert_eq!(rect_of(tester, &sheet_key).top, 0.0);
8073
8074            // Dismiss the bottom sheet.
8075            tester.tap(find::text("Close"));
8076            tester.pump();
8077
8078            // The bottom sheet is dismissed.
8079            assert!(
8080                sheet_key
8081                    .current_context(&tester.cell.borrow_mut())
8082                    .is_none()
8083            );
8084        });
8085    }
8086
8087    fn is_mounted(tester: &WidgetTester, key: &GlobalKey) -> bool {
8088        key.current_context(&tester.cell.borrow_mut()).is_some()
8089    }
8090
8091    // 'can rebuild and remove bottomSheet at the same time'.
8092    #[test]
8093    fn a_bottom_sheet_on_its_way_out_survives_a_rebuild() {
8094        test_widgets(|tester| {
8095            let theme_is_light = Rc::new(Cell::new(true));
8096            let default_bottom_sheet = Rc::new(Cell::new(Some(true)));
8097            let bottom_sheet_key1 = GlobalKey::new();
8098            let bottom_sheet_key2 = GlobalKey::new();
8099            let set_state: Rc<RefCell<Option<StateSetter>>> = Rc::new(RefCell::new(None));
8100
8101            let root = StatefulBuilder::new({
8102                let theme_is_light = Rc::clone(&theme_is_light);
8103                let default_bottom_sheet = Rc::clone(&default_bottom_sheet);
8104                let set_state = Rc::clone(&set_state);
8105                let (key1, key2) = (bottom_sheet_key1.clone(), bottom_sheet_key2.clone());
8106                move |app, _context, state_setter| {
8107                    *set_state.borrow_mut() = Some(state_setter);
8108                    let theme = if theme_is_light.get() {
8109                        ThemeData::new(app)
8110                    } else {
8111                        ThemeData::dark(app, None)
8112                    };
8113                    let sheet = |key: &GlobalKey, color: Color| {
8114                        Container::new()
8115                            .key(key.clone().into())
8116                            .width(f64::INFINITY)
8117                            .height(100.0)
8118                            .color(color)
8119                            .child(waft_widgets::Text::new("BottomSheet"))
8120                            .into_widget()
8121                    };
8122                    let mut scaffold = Scaffold::new().body(placeholder(None));
8123                    match default_bottom_sheet.get() {
8124                        None => {}
8125                        Some(true) => {
8126                            scaffold = scaffold.bottom_sheet(sheet(&key1, Colors::BLUE.primary()))
8127                        }
8128                        Some(false) => {
8129                            scaffold = scaffold.bottom_sheet(sheet(&key2, Colors::RED.primary()))
8130                        }
8131                    }
8132                    // Dart's MaterialApp animates a theme change, which is what keeps the sheet
8133                    // from rebuilding until its exit animation ends.
8134                    material_app(theme, scaffold.into_widget())
8135                }
8136            })
8137            .into_widget();
8138            tester.pump_widget(root);
8139            let set = |tester: &WidgetTester, change: &mut dyn FnMut(&mut App)| {
8140                let set_state = set_state.borrow().clone().expect("built");
8141                set_state(&mut tester.cell.borrow_mut(), change);
8142            };
8143
8144            assert!(is_mounted(tester, &bottom_sheet_key1));
8145            assert!(!is_mounted(tester, &bottom_sheet_key2));
8146
8147            // Change to the other bottomSheet.
8148            set(tester, &mut |_app| default_bottom_sheet.set(Some(false)));
8149            assert!(is_mounted(tester, &bottom_sheet_key1));
8150            assert!(!is_mounted(tester, &bottom_sheet_key2));
8151            tester.pump_and_settle();
8152            assert!(!is_mounted(tester, &bottom_sheet_key1));
8153            assert!(is_mounted(tester, &bottom_sheet_key2));
8154
8155            // Set bottomSheet to null, which starts its exit animation.
8156            set(tester, &mut |_app| default_bottom_sheet.set(None));
8157            assert!(!is_mounted(tester, &bottom_sheet_key1));
8158            assert!(is_mounted(tester, &bottom_sheet_key2));
8159
8160            // While the bottomSheet is on the way out, change the theme to cause it to
8161            // rebuild.
8162            set(tester, &mut |_app| theme_is_light.set(false));
8163            assert!(!is_mounted(tester, &bottom_sheet_key1));
8164            assert!(is_mounted(tester, &bottom_sheet_key2));
8165
8166            // The most recent bottomSheet remains on screen during the exit animation.
8167            tester.pump_by(Duration::from_millis(200));
8168            assert!(!is_mounted(tester, &bottom_sheet_key1));
8169            assert!(is_mounted(tester, &bottom_sheet_key2));
8170
8171            // After animating out, the bottomSheet is gone.
8172            tester.pump_and_settle();
8173            assert!(!is_mounted(tester, &bottom_sheet_key1));
8174            assert!(!is_mounted(tester, &bottom_sheet_key2));
8175        });
8176    }
8177
8178    fn draggable_sheet(
8179        controller: Ref<DraggableScrollableController>,
8180        child: fn() -> WidgetRef,
8181    ) -> DraggableScrollableSheet {
8182        DraggableScrollableSheet::new(Rc::new(move |_app, _context, scroll_controller| {
8183            SingleChildScrollView::new()
8184                .controller(scroll_controller)
8185                .child(child())
8186                .into_widget()
8187        }))
8188        .expand(false)
8189        .controller(controller)
8190    }
8191
8192    /// Dart's `find.descendant(of: find.byType(Scaffold), matching: find.byType(ModalBarrier))`.
8193    fn modal_barriers(tester: &WidgetTester) -> Vec<waft_widgets::AnyElement> {
8194        let scaffold = find::by_type::<Scaffold>().evaluate(tester)[0];
8195        find::by_type::<ModalBarrier>()
8196            .evaluate(tester)
8197            .into_iter()
8198            .filter(|barrier| tester.ancestors(*barrier).contains(&scaffold))
8199            .collect()
8200    }
8201
8202    // 'showBottomSheet removes scrim when draggable sheet is dismissed'.
8203    #[test]
8204    fn closing_a_shown_draggable_sheet_removes_its_scrim() {
8205        test_widgets(|tester| {
8206            let draggable_controller =
8207                DraggableScrollableController::new(&mut tester.cell.borrow_mut());
8208            let scaffold_key = GlobalKey::new();
8209            pump_app(tester, |_app| {
8210                Scaffold::new()
8211                    .key(scaffold_key.clone().into())
8212                    .body(Center::new().child(waft_widgets::Text::new("body")))
8213                    .into_widget()
8214            });
8215
8216            let scaffold = scaffold_state(tester, &scaffold_key);
8217            let sheet_controller = show_sheet(
8218                &mut tester.cell.borrow_mut(),
8219                scaffold,
8220                {
8221                    let draggable_controller = draggable_controller.clone();
8222                    move |_app, _context| {
8223                        draggable_sheet(draggable_controller.clone(), || placeholder(None))
8224                            .into_widget()
8225                    }
8226                },
8227                None,
8228            );
8229
8230            tester.pump();
8231            assert_eq!(find::by_type::<BottomSheet>().evaluate(tester).len(), 1);
8232
8233            // The scrim is not present yet.
8234            assert!(modal_barriers(tester).is_empty());
8235
8236            // Expand the sheet to 80% of parent height to show the scrim.
8237            draggable_controller.jump_to(&mut tester.cell.borrow_mut(), 0.8);
8238            tester.pump();
8239            assert_eq!(modal_barriers(tester).len(), 1);
8240
8241            // Dismiss the sheet.
8242            sheet_controller.close(&mut tester.cell.borrow_mut());
8243            tester.pump_and_settle();
8244
8245            // The scrim should be gone.
8246            assert!(modal_barriers(tester).is_empty());
8247        });
8248    }
8249
8250    const K_BOTTOM_SHEET_DOMINATES: f64 = 0.3;
8251
8252    // 'Floating action button shrinks when bottom sheet becomes dominant'.
8253    #[test]
8254    fn the_floating_action_button_shrinks_as_a_draggable_bottom_sheet_dominates() {
8255        test_widgets(|tester| {
8256            let draggable_controller =
8257                DraggableScrollableController::new(&mut tester.cell.borrow_mut());
8258            pump_app(tester, |_app| {
8259                Scaffold::new()
8260                    .floating_action_button(
8261                        FloatingActionButton::new(None)
8262                            .key(KeyRef::Local(Rc::new(ValueKey::new("one".to_string()))))
8263                            .child(waft_widgets::Text::new("1")),
8264                    )
8265                    .bottom_sheet(draggable_sheet(draggable_controller.clone(), || {
8266                        SizedBox::new().into_widget()
8267                    }))
8268                    .into_widget()
8269            });
8270
8271            let get_scale = |tester: &WidgetTester| {
8272                let scale =
8273                    tester.element(find::by_type::<waft_widgets::Animated<ScaleTransition>>());
8274                let scale = tester
8275                    .widget(scale, |scale: &waft_widgets::Animated<ScaleTransition>| {
8276                        scale.0.scale()
8277                    });
8278                scale.value(&tester.cell.borrow())
8279            };
8280
8281            for i in 0..=10 {
8282                let extent = f64::from(i) / 10.0;
8283                draggable_controller.jump_to(&mut tester.cell.borrow_mut(), extent);
8284
8285                let extent_remaining = 1.0 - extent;
8286                if extent_remaining < K_BOTTOM_SHEET_DOMINATES {
8287                    let vis_value = extent_remaining * K_BOTTOM_SHEET_DOMINATES * 10.0;
8288                    // since FAB uses easeIn curve, we're testing this by using the fact that
8289                    // easeIn curve is always less than or equal to x=y curve.
8290                    assert!(get_scale(tester) <= vis_value, "extent {extent}");
8291                } else {
8292                    assert_eq!(get_scale(tester), 1.0, "extent {extent}");
8293                }
8294            }
8295        });
8296    }
8297
8298    // 'Scaffold shows scrim when bottom sheet becomes dominant'.
8299    #[test]
8300    fn the_scaffold_shows_a_scrim_as_a_draggable_bottom_sheet_dominates() {
8301        test_widgets(|tester| {
8302            let draggable_controller =
8303                DraggableScrollableController::new(&mut tester.cell.borrow_mut());
8304            const K_MIN_BOTTOM_SHEET_SCRIM_OPACITY: f64 = 0.1;
8305            const K_MAX_BOTTOM_SHEET_SCRIM_OPACITY: f64 = 0.6;
8306            pump_app(tester, |_app| {
8307                Scaffold::new()
8308                    .bottom_sheet(draggable_sheet(draggable_controller.clone(), || {
8309                        SizedBox::new().into_widget()
8310                    }))
8311                    .into_widget()
8312            });
8313
8314            let get_opacity = |tester: &WidgetTester| {
8315                let barrier = modal_barriers(tester)[0];
8316                tester.widget(barrier, |barrier: &ModalBarrier| {
8317                    barrier.color.expect("a coloured barrier").a
8318                })
8319            };
8320            let get_expected_opacity = |vis_value: f64| {
8321                f64::max(
8322                    K_MIN_BOTTOM_SHEET_SCRIM_OPACITY,
8323                    K_MAX_BOTTOM_SHEET_SCRIM_OPACITY - vis_value,
8324                )
8325            };
8326
8327            for i in 0..=10 {
8328                let extent = f64::from(i) / 10.0;
8329                draggable_controller.jump_to(&mut tester.cell.borrow_mut(), extent);
8330                tester.pump();
8331
8332                let extent_remaining = 1.0 - extent;
8333                if extent_remaining < K_BOTTOM_SHEET_DOMINATES {
8334                    let vis_value = extent_remaining * K_BOTTOM_SHEET_DOMINATES * 10.0;
8335
8336                    assert_eq!(modal_barriers(tester).len(), 1, "extent {extent}");
8337                    assert_close_to(get_opacity(tester), get_expected_opacity(vis_value), 0.02);
8338                } else {
8339                    assert!(modal_barriers(tester).is_empty(), "extent {extent}");
8340                }
8341            }
8342        });
8343    }
8344
8345    // 'Scaffold uses bottomSheetScrimBuilder if defined'.
8346    #[test]
8347    fn the_scaffold_builds_its_scrim_with_the_bottom_sheet_scrim_builder() {
8348        test_widgets(|tester| {
8349            let draggable_controller =
8350                DraggableScrollableController::new(&mut tester.cell.borrow_mut());
8351            let scrim_key = GlobalKey::new();
8352            pump_app(tester, |_app| {
8353                let scrim_key = scrim_key.clone();
8354                Scaffold::new()
8355                    .bottom_sheet_scrim_builder(move |_app, _context, animation| {
8356                        let scrim_key = scrim_key.clone();
8357                        Some(
8358                            ListenableBuilder::new(
8359                                Rc::new(animation.clone()),
8360                                move |app, _context, _child| {
8361                                    #[allow(deprecated)]
8362                                    let color = Colors::BLACK.with_opacity(animation.value(app));
8363                                    ColoredBox::new(color)
8364                                        .key(scrim_key.clone().into())
8365                                        .into_widget()
8366                                },
8367                            )
8368                            .into_widget(),
8369                        )
8370                    })
8371                    .bottom_sheet(draggable_sheet(draggable_controller.clone(), || {
8372                        SizedBox::new().into_widget()
8373                    }))
8374                    .into_widget()
8375            });
8376
8377            let get_opacity = |tester: &WidgetTester| {
8378                let scrim = scrim_key
8379                    .current_context(&tester.cell.borrow_mut())
8380                    .expect("a scrim");
8381                tester.widget(scrim, |scrim: &ColoredBox| scrim.color.color().a)
8382            };
8383
8384            for i in 0..=10 {
8385                let extent = f64::from(i) / 10.0;
8386                draggable_controller.jump_to(&mut tester.cell.borrow_mut(), extent);
8387                tester.pump();
8388
8389                let extent_remaining = 1.0 - extent;
8390                if extent_remaining < K_BOTTOM_SHEET_DOMINATES {
8391                    let animation_value = 1.0 - extent_remaining / K_BOTTOM_SHEET_DOMINATES;
8392
8393                    assert!(modal_barriers(tester).is_empty(), "extent {extent}");
8394                    assert!(is_mounted(tester, &scrim_key), "extent {extent}");
8395                    assert_close_to(get_opacity(tester), animation_value, 0.02);
8396                } else {
8397                    assert!(!is_mounted(tester, &scrim_key), "extent {extent}");
8398                }
8399            }
8400        });
8401    }
8402
8403    // "Closing bottom sheet & removing FAB at the same time doesn't throw assertion".
8404    #[test]
8405    fn closing_a_bottom_sheet_while_removing_the_floating_action_button_does_not_assert() {
8406        test_widgets(|tester| {
8407            let bottom_sheet_key = GlobalKey::new();
8408            let controller: Rc<RefCell<Option<Rc<PersistentBottomSheetController>>>> =
8409                Rc::new(RefCell::new(None));
8410            let show = Rc::new(Cell::new(true));
8411            let fab_key = GlobalKey::new();
8412            let root = StatefulBuilder::new({
8413                let controller = Rc::clone(&controller);
8414                let show = Rc::clone(&show);
8415                let bottom_sheet_key = bottom_sheet_key.clone();
8416                let fab_key = fab_key.clone();
8417                move |app, _context, set_state| {
8418                    let controller = Rc::clone(&controller);
8419                    let bottom_sheet_key = bottom_sheet_key.clone();
8420                    let mut scaffold = Scaffold::new().body(Center::new().child(Builder::new(
8421                        move |_app, context| {
8422                            let controller = Rc::clone(&controller);
8423                            let bottom_sheet_key = bottom_sheet_key.clone();
8424                            ElevatedButton::new(
8425                                Some(Listener::new(move |app| {
8426                                    let current = controller.borrow_mut().take();
8427                                    match current {
8428                                        None => {
8429                                            let bottom_sheet_key = bottom_sheet_key.clone();
8430                                            let shown = crate::bottom_sheet::ShowBottomSheet::new(
8431                                                Rc::new(move |_app, _context| {
8432                                                    Container::new()
8433                                                        .key(bottom_sheet_key.clone().into())
8434                                                        .height(200.0)
8435                                                        .into_widget()
8436                                                }),
8437                                            )
8438                                            .show(app, context);
8439                                            *controller.borrow_mut() = Some(shown);
8440                                        }
8441                                        Some(current) => current.close(app),
8442                                    }
8443                                })),
8444                                Some(waft_widgets::Text::new("BottomSheet")),
8445                            )
8446                            .into_widget()
8447                        },
8448                    )));
8449                    if show.get() {
8450                        let show = Rc::clone(&show);
8451                        scaffold = scaffold.floating_action_button(
8452                            FloatingActionButton::new(Some(Listener::new(move |app| {
8453                                let show = Rc::clone(&show);
8454                                set_state(app, &mut move |_app| show.set(false));
8455                            })))
8456                            .key(fab_key.clone().into()),
8457                        );
8458                    }
8459                    material_app(ThemeData::new(app), scaffold.into_widget())
8460                }
8461            })
8462            .into_widget();
8463            tester.pump_widget(root);
8464
8465            // Show bottom sheet.
8466            tap_elevated_button(tester, "BottomSheet", 1);
8467            tester.pump_and_settle();
8468
8469            // Bottom sheet and FAB are visible.
8470            assert_eq!(
8471                find::by_type::<FloatingActionButton>()
8472                    .evaluate(tester)
8473                    .len(),
8474                1
8475            );
8476            assert!(is_mounted(tester, &bottom_sheet_key));
8477
8478            // Close bottom sheet while removing FAB.
8479            let at = tester.get_center(&fab_key);
8480            tester.tap_at(at, 2);
8481            tester.pump(); // start animation
8482            tap_elevated_button(tester, "BottomSheet", 3);
8483            // Let the animation finish.
8484            tester.pump_and_settle();
8485
8486            // Bottom sheet and FAB are gone.
8487            assert!(
8488                find::by_type::<FloatingActionButton>()
8489                    .evaluate(tester)
8490                    .is_empty()
8491            );
8492            assert!(!is_mounted(tester, &bottom_sheet_key));
8493        });
8494    }
8495
8496    /// Dart's `buildStatusBarTestApp`.
8497    fn build_status_bar_test_app(tester: &mut WidgetTester) {
8498        pump_app(tester, |_app| {
8499            MediaQuery::new(
8500                // status bar
8501                MediaQueryData::new().padding(EdgeInsets::only(0.0, 25.0, 0.0, 0.0)),
8502                Scaffold::new().body(
8503                    waft_widgets::CustomScrollView::new()
8504                        .primary(true)
8505                        .slivers([
8506                            crate::app_bar::SliverAppBar::new()
8507                                .title(waft_widgets::Text::new("Title"))
8508                                .into_widget(),
8509                            waft_widgets::SliverList::builder(|_app, _context, index| {
8510                                Some(
8511                                    SizedBox::new()
8512                                        .height(100.0)
8513                                        .child(waft_widgets::Text::new(format!("{index}")))
8514                                        .into_widget(),
8515                                )
8516                            })
8517                            .item_count(20)
8518                            .build()
8519                            .into_widget(),
8520                        ]),
8521                ),
8522            )
8523            .into_widget()
8524        });
8525    }
8526
8527    /// Dart's `tester.state<ScrollableState>(find.byType(Scrollable)).position`.
8528    fn scrollable_position(tester: &WidgetTester) -> waft_widgets::AnyScrollPosition {
8529        let scrollables = find::by_type::<waft_widgets::Scrollable>().evaluate(tester);
8530        assert_eq!(scrollables.len(), 1, "one Scrollable");
8531        let app = tester.cell.borrow();
8532        scrollables[0]
8533            .state_handle::<waft_widgets::ScrollableState>(&app)
8534            .expect("a Scrollable element holds a ScrollableState")
8535            .position(&app)
8536    }
8537
8538    // 'Tapping the status bar scrolls to top with ease out curve animation': the binding has
8539    // no status-bar-tap callback yet, so the case calls `ScaffoldState::handle_status_bar_tap`
8540    // where Dart's `simulateStatusBarTap` reaches it through the binding.
8541    #[test]
8542    fn tapping_the_status_bar_scrolls_the_primary_scroll_view_to_the_top_easing_out() {
8543        test_widgets_variant(TargetPlatformVariant::only(TargetPlatform::IOS), |tester| {
8544            const DURATION: u64 = 1000;
8545            let stops = [0.842, 0.959, 0.993, 1.0];
8546            const SCROLL_OFFSET: f64 = 1000.0;
8547
8548            build_status_bar_test_app(tester);
8549            let position = scrollable_position(tester);
8550            position.jump_to(&mut tester.cell.borrow_mut(), SCROLL_OFFSET);
8551
8552            let scaffold = only_scaffold_state(tester);
8553            scaffold.handle_status_bar_tap(&mut tester.cell.borrow_mut());
8554            tester.pump();
8555            assert_eq!(position.pixels(&tester.cell.borrow()), SCROLL_OFFSET);
8556
8557            for (i, stop) in stops.iter().enumerate() {
8558                tester.pump_by(Duration::from_millis(DURATION / stops.len() as u64));
8559                // Scroll pixel position is very long double, compare with floored int
8560                // pixel position
8561                assert_eq!(
8562                    position.pixels(&tester.cell.borrow()) as i64,
8563                    (SCROLL_OFFSET * (1.0 - stop)) as i64,
8564                    "stop {i}"
8565                );
8566            }
8567
8568            // Finally stops at the top.
8569            assert_eq!(position.pixels(&tester.cell.borrow()), 0.0);
8570        });
8571    }
8572
8573    /// Dart's `tester.state<ScaffoldState>(find.byType(Scaffold))`.
8574    fn only_scaffold_state(tester: &WidgetTester) -> Handle<ScaffoldState> {
8575        let scaffolds = find::by_type::<Scaffold>().evaluate(tester);
8576        assert_eq!(scaffolds.len(), 1, "one Scaffold");
8577        scaffolds[0]
8578            .state_handle::<ScaffoldState>(&tester.cell.borrow())
8579            .expect("a Scaffold element holds a ScaffoldState")
8580    }
8581
8582    /// A location as a `ValueNotifier`'s value, equal by identity as Dart's locations are.
8583    #[derive(Clone)]
8584    struct LocationValue(FloatingActionButtonLocationRef);
8585
8586    impl PartialEq for LocationValue {
8587        fn eq(&self, other: &LocationValue) -> bool {
8588            Rc::ptr_eq(&self.0, &other.0)
8589        }
8590    }
8591
8592    /// Whether the `Builder` that builds the scaffold's `CustomMultiChildLayout`, under its
8593    /// `ScrollNotificationObserver`, is dirty: Dart's `checkDirty`.
8594    fn scaffold_layout_builder_dirty(app: &mut App) -> Option<bool> {
8595        let root = WidgetsBinding::instance(app).root_element(app)?;
8596        let mut pending = vec![root];
8597        let mut layout = None;
8598        while let Some(element) = pending.pop() {
8599            if downcast_widget::<CustomMultiChildLayout>(&**element.widget(app)).is_some() {
8600                layout = Some(element);
8601                break;
8602            }
8603            element.visit_children(app, &mut |child| pending.push(child));
8604        }
8605        let layout = layout?;
8606        let mut builder = None;
8607        let mut ancestor = layout.parent(app);
8608        while let Some(current) = ancestor {
8609            if downcast_widget::<ScrollNotificationObserver>(&**current.widget(app)).is_some() {
8610                break;
8611            }
8612            if builder.is_none() && downcast_widget::<Builder>(&**current.widget(app)).is_some() {
8613                builder = Some(current);
8614            }
8615            ancestor = current.parent(app);
8616        }
8617        builder.map(|builder| builder.dirty(app))
8618    }
8619
8620    // 'Scaffold FAB animates without rebuilding'.
8621    #[test]
8622    fn moving_the_floating_action_button_does_not_rebuild_the_scaffolds_layout() {
8623        test_widgets(|tester| {
8624            let dirty = Rc::new(Cell::new(None));
8625            let fab_location =
8626                tester
8627                    .cell
8628                    .borrow_mut()
8629                    .create(waft_foundation::ValueNotifier::new(LocationValue(
8630                        <dyn FloatingActionButtonLocation>::center_docked(),
8631                    )));
8632            let builder_key = GlobalKey::new();
8633            pump_app(tester, |_app| {
8634                let dirty = Rc::clone(&dirty);
8635                waft_widgets::ValueListenableBuilder::new(
8636                    Rc::new(fab_location.clone()),
8637                    move |app, _context, location: &LocationValue, _child| {
8638                        dirty.set(scaffold_layout_builder_dirty(app));
8639
8640                        Scaffold::new()
8641                            .body(SizedBox::expand())
8642                            .floating_action_button(FloatingActionButton::new(Some(Listener::new(
8643                                |_| {},
8644                            ))))
8645                            .floating_action_button_location(Rc::clone(&location.0))
8646                            .into_widget()
8647                    },
8648                )
8649                .key(builder_key.clone().into())
8650                .into_widget()
8651            });
8652
8653            // Switch the FAB location to trigger the animation.
8654            fab_location.set_value(
8655                &mut tester.cell.borrow_mut(),
8656                LocationValue(<dyn FloatingActionButtonLocation>::end_float()),
8657            );
8658            tester.pump_by(crate::Durations::SHORT1);
8659
8660            // Trigger a rebuild to update the "dirty" value.
8661            {
8662                let mut app = tester.cell.borrow_mut();
8663                let element = builder_key.current_context(&app).expect("mounted");
8664                element.mark_needs_build(&mut app);
8665            }
8666            tester.pump_by(crate::Durations::SHORT1);
8667
8668            // The element that builds the Scaffold's CustomMultiChildLayout should not be dirty.
8669            assert_eq!(dirty.get(), Some(false));
8670        });
8671    }
8672
8673    // The cases that waited for `AppBar`.
8674
8675    /// `Scaffold(appBar: AppBar(title: Text('Title')), ..)`.
8676    fn with_title_app_bar(scaffold: Scaffold) -> Scaffold {
8677        scaffold.app_bar(PreferredSizeWidgetRef::new(
8678            AppBar::new().title(waft_widgets::Text::new("Title")),
8679        ))
8680    }
8681
8682    /// Dart's `boilerplate`: `Localizations(en-us, ..)` and a left-to-right `Directionality`.
8683    fn boilerplate(child: WidgetRef) -> WidgetRef {
8684        waft_widgets::Localizations::new(
8685            waft_embedder::Locale::new("en").country_code("us"),
8686            vec![
8687                waft_widgets::DefaultWidgetsLocalizations::delegate(),
8688                crate::material_localizations::DefaultMaterialLocalizations::delegate(),
8689            ],
8690        )
8691        .child(Directionality::new(TextDirection::Ltr, child))
8692        .into_widget()
8693    }
8694
8695    // 'Scaffold control test'.
8696    #[test]
8697    fn the_app_bar_takes_its_height_from_the_top_of_the_body() {
8698        test_widgets(|tester| {
8699            let body_key = GlobalKey::new();
8700            pump_app(tester, |_app| {
8701                with_title_app_bar(Scaffold::new())
8702                    .body(Container::new().key(body_key.clone().into()))
8703                    .into_widget()
8704            });
8705            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 544.0));
8706
8707            let insets = MediaQueryData::new().view_insets(EdgeInsets::only(0.0, 0.0, 0.0, 100.0));
8708            tester.pump_widget(boilerplate(
8709                MediaQuery::new(
8710                    insets.clone(),
8711                    with_title_app_bar(Scaffold::new())
8712                        .body(Container::new().key(body_key.clone().into())),
8713                )
8714                .into_widget(),
8715            ));
8716            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 444.0));
8717
8718            tester.pump_widget(boilerplate(
8719                MediaQuery::new(
8720                    insets,
8721                    with_title_app_bar(Scaffold::new())
8722                        .body(Container::new().key(body_key.clone().into()))
8723                        .resize_to_avoid_bottom_inset(false),
8724                )
8725                .into_widget(),
8726            ));
8727            assert_eq!(size_of(tester, &body_key), Size::new(800.0, 544.0));
8728        });
8729    }
8730
8731    /// Dart's `tester.widget<Icon>(find.byType(Icon)).icon`: the one onstage `Icon`.
8732    fn only_onstage_icon(tester: &WidgetTester) -> Option<waft_widgets::IconData> {
8733        let icons: Vec<_> = find::by_type::<waft_widgets::Icon>()
8734            .evaluate(tester)
8735            .into_iter()
8736            .filter(|icon| tester.is_onstage(*icon))
8737            .collect();
8738        assert_eq!(icons.len(), 1);
8739        tester.widget(icons[0], |icon: &waft_widgets::Icon| icon.icon.clone())
8740    }
8741
8742    /// Dart's `Navigator.push(context, route)` of a page route whose page is `page`.
8743    fn push_page(
8744        tester: &WidgetTester,
8745        context: BuildContext,
8746        fullscreen_dialog: bool,
8747        page: fn() -> WidgetRef,
8748    ) {
8749        let mut app = tester.cell.borrow_mut();
8750        let page_builder: waft_widgets::RoutePageBuilder =
8751            Rc::new(move |_app, _context, _, _| page());
8752        let route = waft_widgets::PageRouteBuilder::new(&mut app, page_builder)
8753            .fullscreen_dialog(&mut app, fullscreen_dialog);
8754        drop(waft_widgets::Navigator::push(
8755            &mut app,
8756            context,
8757            route.erase(),
8758        ));
8759    }
8760
8761    /// Dart's `back arrow` group's `expectBackIcon`, with the scaffold pushed from the home
8762    /// route as `Navigator.pushNamed` does.
8763    fn back_icon_on(platform: TargetPlatform) -> Option<waft_widgets::IconData> {
8764        let icon = std::sync::Mutex::new(None);
8765        test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
8766            let root_key = GlobalKey::new();
8767            pump_app(tester, |_app| {
8768                Container::new()
8769                    .key(root_key.clone().into())
8770                    .child(waft_widgets::Text::new("Home"))
8771                    .into_widget()
8772            });
8773            let context = root_key
8774                .current_context(&tester.cell.borrow_mut())
8775                .expect("the home route is mounted");
8776            push_page(tester, context, false, || {
8777                Scaffold::new()
8778                    .app_bar(PreferredSizeWidgetRef::new(AppBar::new()))
8779                    .body(waft_widgets::Text::new("Scaffold"))
8780                    .into_widget()
8781            });
8782            tester.pump();
8783            tester.pump_by(Duration::from_secs(1));
8784            *icon.lock().expect("the icon") = only_onstage_icon(tester);
8785        });
8786        icon.into_inner().expect("the icon")
8787    }
8788
8789    #[test]
8790    fn the_back_arrow_is_the_android_arrow_on_android_and_fuchsia() {
8791        for platform in [TargetPlatform::Android, TargetPlatform::Fuchsia] {
8792            assert_eq!(
8793                back_icon_on(platform),
8794                Some(crate::Icons::arrow_back()),
8795                "on {platform:?}"
8796            );
8797        }
8798    }
8799
8800    #[test]
8801    fn the_back_arrow_is_the_ios_arrow_on_ios_and_macos() {
8802        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
8803            assert_eq!(
8804                back_icon_on(platform),
8805                Some(crate::Icons::arrow_back_ios_new_rounded()),
8806                "on {platform:?}"
8807            );
8808        }
8809    }
8810
8811    // 'Close button shows correctly with PageRouteBuilder', on every platform. Dart's
8812    // `MaterialPageRoute` and custom page route cases wait for `MaterialPageRoute`.
8813    #[test]
8814    fn a_fullscreen_dialog_page_route_gets_a_close_button() {
8815        for platform in [
8816            TargetPlatform::Android,
8817            TargetPlatform::Fuchsia,
8818            TargetPlatform::IOS,
8819            TargetPlatform::Linux,
8820            TargetPlatform::MacOS,
8821            TargetPlatform::Windows,
8822        ] {
8823            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
8824                let body_key = GlobalKey::new();
8825                pump_app(tester, |_app| {
8826                    Scaffold::new()
8827                        .app_bar(PreferredSizeWidgetRef::new(AppBar::new()))
8828                        .body(waft_widgets::Text::new("Page 1").key(body_key.clone().into()))
8829                        .into_widget()
8830                });
8831                let context = body_key
8832                    .current_context(&tester.cell.borrow_mut())
8833                    .expect("the first page is mounted");
8834                push_page(tester, context, true, || {
8835                    Scaffold::new()
8836                        .app_bar(PreferredSizeWidgetRef::new(AppBar::new()))
8837                        .body(waft_widgets::Text::new("Page 2"))
8838                        .into_widget()
8839                });
8840                tester.pump();
8841                tester.pump_by(Duration::from_secs(1));
8842
8843                assert_eq!(
8844                    only_onstage_icon(tester),
8845                    Some(crate::Icons::close()),
8846                    "didn't find close icon for pageRouteBuilder on {platform:?}"
8847                );
8848                let close_key = waft_widgets::StandardComponentType::CloseButton.key();
8849                let close_buttons = {
8850                    let elements = tester.elements();
8851                    let app = tester.cell.borrow();
8852                    elements
8853                        .into_iter()
8854                        .filter(|element| {
8855                            waft_widgets::keys_equal(element.widget(&app).key(), Some(&close_key))
8856                        })
8857                        .count()
8858                };
8859                assert_eq!(
8860                    close_buttons, 1,
8861                    "didn't find close button for pageRouteBuilder on {platform:?}"
8862                );
8863            });
8864        }
8865    }
8866
8867    #[test]
8868    fn has_app_bar_and_app_bar_max_height_follow_the_app_bar() {
8869        test_widgets(|tester| {
8870            let scaffold_key = GlobalKey::new();
8871            tester.pump_widget(boilerplate(
8872                MediaQuery::new(
8873                    MediaQueryData::new().padding(EdgeInsets::only(0.0, 20.0, 0.0, 0.0)),
8874                    with_title_app_bar(Scaffold::new().key(scaffold_key.clone().into())),
8875                )
8876                .into_widget(),
8877            ));
8878            let state = scaffold_state(tester, &scaffold_key);
8879            {
8880                let app = tester.cell.borrow();
8881                assert!(state.has_app_bar(&app));
8882                assert_eq!(
8883                    state.app_bar_max_height(&app),
8884                    Some(K_TOOLBAR_HEIGHT_FOR_TESTS + 20.0)
8885                );
8886            }
8887
8888            tester.pump_widget(boilerplate(
8889                MediaQuery::new(
8890                    MediaQueryData::new().padding(EdgeInsets::only(0.0, 20.0, 0.0, 0.0)),
8891                    Scaffold::new().key(scaffold_key.clone().into()),
8892                )
8893                .into_widget(),
8894            ));
8895            let app = tester.cell.borrow();
8896            assert!(!state.has_app_bar(&app));
8897        });
8898    }
8899
8900    const K_TOOLBAR_HEIGHT_FOR_TESTS: f64 = crate::constants::K_TOOLBAR_HEIGHT;
8901}