Skip to main content

waft_material/
switch_list_tile.rs

1//! Flutter counterpart: material_ui's `switch_list_tile.dart`.
2//!
3//! The thumb images (`activeThumbImage`, `inactiveThumbImage` and their error listeners)
4//! wait with [`Switch`]'s, on painting's `DecorationImage`.
5#![allow(deprecated)]
6
7use std::fmt::{self, Debug};
8use std::rc::Rc;
9
10use waft_embedder::Color;
11use waft_foundation::{App, Ref, ValueChanged};
12use waft_gestures::{DragStartBehavior, GestureTapCallback};
13use waft_painting::{EdgeInsetsGeometry, ShapeBorderRef};
14use waft_services::MouseCursorRef;
15use waft_widgets::{
16    BuildContext, ExcludeFocus, FocusNodeRef, Icon, IntoWidget, KeyRef, MergeSemantics,
17    StatelessWidget, WidgetRef, WidgetState, WidgetStatePropertyRef, WidgetStates,
18    WidgetStatesController,
19};
20
21use crate::list_tile::{ListTile, ListTileControlAffinity};
22use crate::list_tile_theme::ListTileTheme;
23use crate::switch::Switch;
24use crate::switch_theme::SwitchTheme;
25use crate::theme::Theme;
26use crate::theme_data::{MaterialTapTargetSize, VisualDensity};
27
28/// Dart's `_SwitchListTileType`.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30enum SwitchListTileType {
31    Material,
32    Adaptive,
33}
34
35/// A [`ListTile`] with a [`Switch`]. In other words, a switch with a label.
36///
37/// The entire list tile is interactive: tapping anywhere in the tile toggles
38/// the switch. Tapping and dragging the [`Switch`] also triggers the
39/// [`on_changed`](Self::on_changed) callback.
40///
41/// To ensure that [`on_changed`](Self::on_changed) correctly triggers, the state passed
42/// into [`value`](Self::value) must be properly managed. This is typically done by invoking
43/// `State::set_state` in [`on_changed`](Self::on_changed) to toggle the state value.
44///
45/// The [`value`](Self::value), [`on_changed`](Self::on_changed) and
46/// [`active_thumb_color`](Self::active_thumb_color) properties of this widget are identical to
47/// the similarly-named properties on the [`Switch`] widget.
48///
49/// The [`title`](Self::title), [`subtitle`](Self::subtitle),
50/// [`is_three_line`](Self::is_three_line), and [`dense`](Self::dense) properties are like
51/// those of the same name on [`ListTile`].
52///
53/// The [`selected`](Self::selected) property on this widget is similar to the
54/// [`ListTile::selected`] property. This tile's [`active_thumb_color`](Self::active_thumb_color)
55/// is used for the selected item's text color, or the theme's `SwitchThemeData::overlay_color`
56/// if [`active_thumb_color`](Self::active_thumb_color) is null.
57///
58/// This widget does not coordinate the [`selected`](Self::selected) state and the
59/// [`value`](Self::value); to have the list tile appear selected when the
60/// switch button is on, use the same value for both.
61///
62/// The switch is shown on the right by default in left-to-right languages (i.e.
63/// in the [`ListTile::trailing`] slot) which can be changed using
64/// [`control_affinity`](Self::control_affinity). The [`secondary`](Self::secondary) widget is
65/// placed in the [`ListTile::leading`] slot.
66///
67/// This widget requires a `Material` widget ancestor in the tree to paint
68/// itself on, which is typically provided by the app's `Scaffold`.
69/// The [`tile_color`](Self::tile_color), and [`selected_tile_color`](Self::selected_tile_color)
70/// are not painted by the [`SwitchListTile`] itself but by the `Material` widget ancestor. In
71/// this case, one can wrap a `Material` widget around the [`SwitchListTile`].
72///
73/// ## Performance considerations when wrapping [`SwitchListTile`] with `Material`
74///
75/// Wrapping a large number of [`SwitchListTile`]s individually with `Material`s
76/// is expensive. Consider only wrapping the [`SwitchListTile`]s that require it
77/// or include a common `Material` ancestor where possible.
78///
79/// To show the [`SwitchListTile`] as disabled, pass null as the
80/// [`on_changed`](Self::on_changed) callback.
81///
82/// ## SwitchListTile isn't exactly what I want
83///
84/// If the way SwitchListTile pads and positions its elements isn't quite what
85/// you're looking for, you can create custom labeled switch widgets by
86/// combining [`Switch`] with other widgets, such as `Text`, `Padding` and
87/// `InkWell`.
88///
89/// See also:
90///
91///  * [`ListTileTheme`], which can be used to affect the style of list tiles,
92///    including switch list tiles.
93///  * `CheckboxListTile`, a similar widget for checkboxes.
94///  * `RadioListTile`, a similar widget for radio buttons.
95///  * [`ListTile`] and [`Switch`], the widgets from which this widget is made.
96pub struct SwitchListTile {
97    pub key: Option<KeyRef>,
98    /// Whether this switch is checked.
99    pub value: bool,
100    /// Called when the user toggles the switch on or off.
101    ///
102    /// The switch passes the new value to the callback but does not actually
103    /// change state until the parent widget rebuilds the switch tile with the
104    /// new value.
105    ///
106    /// If null, the switch will be displayed as disabled.
107    pub on_changed: Option<ValueChanged<bool>>,
108    /// The color to use when this switch is on.
109    ///
110    /// Defaults to `ColorScheme::secondary` of the current [`Theme`].
111    #[deprecated(
112        note = "Use activeThumbColor or activeTrackColor instead. This feature was deprecated after v3.31.0-2.0.pre."
113    )]
114    pub active_color: Option<Color>,
115    /// The color to use on the thumb when this switch is on.
116    ///
117    /// Defaults to `ColorScheme::secondary` of the current [`Theme`].
118    pub active_thumb_color: Option<Color>,
119    /// The color to use on the track when this switch is on.
120    ///
121    /// Defaults to `ColorScheme::secondary` with the opacity set at 50%.
122    ///
123    /// Ignored if created with [`SwitchListTile::adaptive`].
124    pub active_track_color: Option<Color>,
125    /// The color to use on the thumb when this switch is off.
126    ///
127    /// Defaults to the colors described in the Material design specification.
128    ///
129    /// Ignored if created with [`SwitchListTile::adaptive`].
130    pub inactive_thumb_color: Option<Color>,
131    /// The color to use on the track when this switch is off.
132    ///
133    /// Defaults to the colors described in the Material design specification.
134    ///
135    /// Ignored if created with [`SwitchListTile::adaptive`].
136    pub inactive_track_color: Option<Color>,
137    /// The color of this switch's thumb.
138    ///
139    /// Resolved in the following states:
140    ///  * [`WidgetState::Selected`].
141    ///  * [`WidgetState::Hovered`].
142    ///  * [`WidgetState::Disabled`].
143    ///
144    /// If null, then the value of [`active_thumb_color`](Self::active_thumb_color) is used in
145    /// the selected state and [`inactive_thumb_color`](Self::inactive_thumb_color) in the
146    /// default state. If that is also null, then the value of `SwitchThemeData::thumb_color`
147    /// is used. If that is also null, The default value is used.
148    pub thumb_color: Option<WidgetStatePropertyRef<Option<Color>>>,
149    /// The color of this switch's track.
150    ///
151    /// Resolved in the following states:
152    ///  * [`WidgetState::Selected`].
153    ///  * [`WidgetState::Hovered`].
154    ///  * [`WidgetState::Disabled`].
155    ///
156    /// If null, then the value of [`active_track_color`](Self::active_track_color) is used in
157    /// the selected state and [`inactive_track_color`](Self::inactive_track_color) in the
158    /// default state. If that is also null, then the value of `SwitchThemeData::track_color`
159    /// is used. If that is also null, then the default value is used.
160    pub track_color: Option<WidgetStatePropertyRef<Option<Color>>>,
161    /// The outline color of this switch's track.
162    ///
163    /// The [`ListTile`] will be focused when this [`SwitchListTile`] requests focus,
164    /// so the focused outline color of the switch will be ignored.
165    ///
166    /// In Material 3, the outline color defaults to transparent in the selected
167    /// state and `ColorScheme::outline` in the unselected state. In Material 2,
168    /// the [`Switch`] track has no outline.
169    pub track_outline_color: Option<WidgetStatePropertyRef<Option<Color>>>,
170    /// The icon to use on the thumb of this switch
171    ///
172    /// Resolved in the following states:
173    ///  * [`WidgetState::Selected`].
174    ///  * [`WidgetState::Hovered`].
175    ///  * [`WidgetState::Disabled`].
176    ///
177    /// If null, then the value of `SwitchThemeData::thumb_icon` is used. If this is
178    /// also null, then the [`Switch`] does not have any icons on the thumb.
179    pub thumb_icon: Option<WidgetStatePropertyRef<Option<Rc<Icon>>>>,
180    /// Configures the minimum size of the tap target.
181    ///
182    /// defaults to [`MaterialTapTargetSize::ShrinkWrap`].
183    pub material_tap_target_size: Option<MaterialTapTargetSize>,
184    /// Determines the way that drag start behavior is handled.
185    pub drag_start_behavior: DragStartBehavior,
186    /// The cursor for a mouse pointer when it enters or is hovering over the
187    /// widget.
188    ///
189    /// If [`mouse_cursor`](Self::mouse_cursor) is a `WidgetStateMouseCursor`,
190    /// `WidgetStateProperty::resolve` is used for the following [`WidgetState`]s:
191    ///
192    ///  * [`WidgetState::Selected`].
193    ///  * [`WidgetState::Hovered`].
194    ///  * [`WidgetState::Disabled`].
195    ///
196    /// If null, then the value of `SwitchThemeData::mouse_cursor` is used. If that
197    /// is also null, then `WidgetStateMouseCursor::clickable` is used.
198    pub mouse_cursor: Option<MouseCursorRef>,
199    /// The color for the switch's `Material`.
200    ///
201    /// Resolves in the following states:
202    ///  * [`WidgetState::Pressed`].
203    ///  * [`WidgetState::Selected`].
204    ///  * [`WidgetState::Hovered`].
205    ///
206    /// If null, then the value of [`active_thumb_color`](Self::active_thumb_color) with alpha
207    /// `K_RADIAL_REACTION_ALPHA` and [`hover_color`](Self::hover_color) is used in the pressed
208    /// and hovered state. If that is also null, the value of `SwitchThemeData::overlay_color`
209    /// is used. If that is also null, then the default value is used in the pressed and
210    /// hovered state.
211    pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
212    /// The splash radius of the circular `Material` ink response.
213    ///
214    /// If null, then the value of `SwitchThemeData::splash_radius` is used. If that
215    /// is also null, then `K_RADIAL_REACTION_RADIUS` is used.
216    pub splash_radius: Option<f64>,
217    /// An optional focus node to use as the focus node for this widget.
218    pub focus_node: Option<FocusNodeRef>,
219    /// Controls the interactive states of the backing [`ListTile`].
220    pub states_controller: Option<Ref<WidgetStatesController>>,
221    /// Handler called when the focus changes.
222    ///
223    /// Called with true if this widget's node gains focus, and false if it loses
224    /// focus.
225    pub on_focus_change: Option<ValueChanged<bool>>,
226    /// True if this widget will be selected as the initial focus when no other
227    /// node in its scope is currently focused.
228    pub autofocus: bool,
229    /// Defines the background color of `ListTile` when [`selected`](Self::selected) is false.
230    pub tile_color: Option<Color>,
231    /// The primary content of the list tile.
232    ///
233    /// Typically a `Text` widget.
234    pub title: Option<WidgetRef>,
235    /// Additional content displayed below the title.
236    ///
237    /// Typically a `Text` widget.
238    pub subtitle: Option<WidgetRef>,
239    /// A widget to display on the opposite side of the tile from the switch.
240    ///
241    /// Typically an `Icon` widget.
242    pub secondary: Option<WidgetRef>,
243    /// Whether this list tile is intended to display three lines of text.
244    ///
245    /// If null, the value from `ListTileThemeData::is_three_line` is used.
246    /// If that is also null, the value from `ThemeData::list_tile_theme` is used.
247    /// If still null, the default value is `false`.
248    pub is_three_line: Option<bool>,
249    /// Whether this list tile is part of a vertically dense list.
250    ///
251    /// If this property is null then its value is based on `ListTileThemeData::dense`.
252    pub dense: Option<bool>,
253    /// The tile's internal padding.
254    ///
255    /// Insets a [`SwitchListTile`]'s contents: its [`title`](Self::title),
256    /// [`subtitle`](Self::subtitle), [`secondary`](Self::secondary), and [`Switch`] widgets.
257    ///
258    /// If null, [`ListTile`]'s default of `EdgeInsets.symmetric(horizontal: 16.0)`
259    /// is used.
260    pub content_padding: Option<EdgeInsetsGeometry>,
261    /// Whether to render icons and text in the [`active_thumb_color`](Self::active_thumb_color).
262    ///
263    /// No effort is made to automatically coordinate the [`selected`](Self::selected) state
264    /// and the [`value`](Self::value) state. To have the list tile appear selected when the
265    /// switch is on, pass the same value to both.
266    ///
267    /// Normally, this property is left to its default value, false.
268    pub selected: bool,
269    /// If adaptive, creates the switch with [`Switch::adaptive`].
270    switch_list_tile_type: SwitchListTileType,
271    /// Defines the position of control and [`secondary`](Self::secondary), relative to text.
272    ///
273    /// By default, the value of [`control_affinity`](Self::control_affinity) is
274    /// [`ListTileControlAffinity::Platform`].
275    pub control_affinity: Option<ListTileControlAffinity>,
276    /// Defines the tile's `InkWell::custom_border` and `Ink::decoration` shape.
277    pub shape: Option<ShapeBorderRef>,
278    /// If non-null, defines the background color when [`SwitchListTile::selected`] is true.
279    pub selected_tile_color: Option<Color>,
280    /// Defines how compact the list tile's layout will be.
281    pub visual_density: Option<VisualDensity>,
282    /// Whether detected gestures should provide acoustic and/or haptic feedback.
283    ///
284    /// See also:
285    ///
286    ///  * `Feedback` for providing platform-specific feedback to certain actions.
287    pub enable_feedback: Option<bool>,
288    /// The horizontal gap between the titles and the leading/trailing widgets.
289    pub horizontal_title_gap: Option<f64>,
290    /// The minimum padding on the top and bottom of the title and subtitle widgets.
291    pub min_vertical_padding: Option<f64>,
292    /// The minimum width allocated for the `ListTile::leading` widget.
293    pub min_leading_width: Option<f64>,
294    /// The minimum height allocated for the `ListTile` widget.
295    pub min_tile_height: Option<f64>,
296    /// The color for the tile's `Material` when a pointer is hovering over it.
297    pub hover_color: Option<Color>,
298    /// Whether to apply the ambient `CupertinoThemeData`.
299    ///
300    /// Read through [`effective_apply_cupertino_theme`](Self::effective_apply_cupertino_theme).
301    pub apply_cupertino_theme: Option<bool>,
302    /// Whether to add button:true to the semantics if onTap is provided.
303    /// This is a temporary flag to help changing the behavior of ListTile onTap semantics.
304    pub internal_add_semantic_for_on_tap: bool,
305}
306
307/// The setters of `SwitchListTile`'s optional arguments that hold a value.
308macro_rules! switch_list_tile_setters {
309    ($($field:ident: $ty:ty => $name:literal),* $(,)?) => {
310        $(
311            #[doc = concat!("Dart `SwitchListTile(", $name, ":)`.")]
312            pub fn $field(mut self, $field: impl Into<$ty>) -> SwitchListTile {
313                self.$field = Some($field.into());
314                self
315            }
316        )*
317    };
318}
319
320/// The setters of `SwitchListTile`'s optional arguments that are widgets.
321macro_rules! switch_list_tile_widget_setters {
322    ($($field:ident => $name:literal),* $(,)?) => {
323        $(
324            #[doc = concat!("Dart `SwitchListTile(", $name, ":)`.")]
325            pub fn $field<K>(mut self, $field: impl IntoWidget<K>) -> SwitchListTile {
326                self.$field = Some($field.into_widget());
327                self
328            }
329        )*
330    };
331}
332
333impl SwitchListTile {
334    /// Creates a combination of a list tile and a switch.
335    ///
336    /// The switch tile itself does not maintain any state. Instead, when the
337    /// state of the switch changes, the widget calls the [`on_changed`](Self::on_changed)
338    /// callback. Most widgets that use a switch will listen for the
339    /// [`on_changed`](Self::on_changed) callback and rebuild the switch tile with a new
340    /// [`value`](Self::value) to update the visual appearance of the switch.
341    ///
342    /// The following arguments are required:
343    ///
344    /// * `value` determines whether this switch is on or off.
345    /// * `on_changed` is called when the user toggles the switch on or off.
346    ///
347    /// Dart's `SwitchListTile` has no `applyCupertinoTheme` parameter: its
348    /// `applyCupertinoTheme` is false, so an
349    /// [`apply_cupertino_theme`](Self::apply_cupertino_theme) set on it is ignored
350    /// ([`effective_apply_cupertino_theme`](Self::effective_apply_cupertino_theme)).
351    pub fn new(value: bool, on_changed: Option<ValueChanged<bool>>) -> SwitchListTile {
352        SwitchListTile::with_type(value, on_changed, SwitchListTileType::Material)
353    }
354
355    /// Creates a Material [`ListTile`] with an adaptive [`Switch`], following
356    /// Material design's
357    /// [Cross-platform guidelines](https://material.io/design/platform-guidance/cross-platform-adaptation.html).
358    ///
359    /// This widget uses [`Switch::adaptive`] to change the graphics of the switch
360    /// component based on the ambient `ThemeData::platform`. On iOS and macOS, a
361    /// `CupertinoSwitch` will be used. On other platforms a Material design
362    /// [`Switch`] will be used.
363    ///
364    /// If a `CupertinoSwitch` is created, the following parameters are
365    /// ignored: [`active_track_color`](Self::active_track_color),
366    /// [`inactive_thumb_color`](Self::inactive_thumb_color),
367    /// [`inactive_track_color`](Self::inactive_track_color).
368    pub fn adaptive(value: bool, on_changed: Option<ValueChanged<bool>>) -> SwitchListTile {
369        SwitchListTile::with_type(value, on_changed, SwitchListTileType::Adaptive)
370    }
371
372    fn with_type(
373        value: bool,
374        on_changed: Option<ValueChanged<bool>>,
375        switch_list_tile_type: SwitchListTileType,
376    ) -> SwitchListTile {
377        SwitchListTile {
378            key: None,
379            value,
380            on_changed,
381            active_color: None,
382            active_thumb_color: None,
383            active_track_color: None,
384            inactive_thumb_color: None,
385            inactive_track_color: None,
386            thumb_color: None,
387            track_color: None,
388            track_outline_color: None,
389            thumb_icon: None,
390            material_tap_target_size: None,
391            drag_start_behavior: DragStartBehavior::Start,
392            mouse_cursor: None,
393            overlay_color: None,
394            splash_radius: None,
395            focus_node: None,
396            states_controller: None,
397            on_focus_change: None,
398            autofocus: false,
399            tile_color: None,
400            title: None,
401            subtitle: None,
402            secondary: None,
403            is_three_line: None,
404            dense: None,
405            content_padding: None,
406            selected: false,
407            switch_list_tile_type,
408            control_affinity: None,
409            shape: None,
410            selected_tile_color: None,
411            visual_density: None,
412            enable_feedback: None,
413            horizontal_title_gap: None,
414            min_vertical_padding: None,
415            min_leading_width: None,
416            min_tile_height: None,
417            hover_color: None,
418            apply_cupertino_theme: None,
419            internal_add_semantic_for_on_tap: false,
420        }
421    }
422
423    /// Dart `SwitchListTile(key:)`.
424    pub fn key(mut self, key: KeyRef) -> SwitchListTile {
425        self.key = Some(key);
426        self
427    }
428
429    /// Dart `SwitchListTile(activeColor:)`.
430    #[deprecated(
431        note = "Use activeThumbColor or activeTrackColor instead. This feature was deprecated after v3.31.0-2.0.pre."
432    )]
433    pub fn active_color(mut self, active_color: Color) -> SwitchListTile {
434        self.active_color = Some(active_color);
435        self
436    }
437
438    switch_list_tile_setters!(
439        active_thumb_color: Color => "activeThumbColor",
440        active_track_color: Color => "activeTrackColor",
441        inactive_thumb_color: Color => "inactiveThumbColor",
442        inactive_track_color: Color => "inactiveTrackColor",
443        thumb_color: WidgetStatePropertyRef<Option<Color>> => "thumbColor",
444        track_color: WidgetStatePropertyRef<Option<Color>> => "trackColor",
445        track_outline_color: WidgetStatePropertyRef<Option<Color>> => "trackOutlineColor",
446        thumb_icon: WidgetStatePropertyRef<Option<Rc<Icon>>> => "thumbIcon",
447        material_tap_target_size: MaterialTapTargetSize => "materialTapTargetSize",
448        mouse_cursor: MouseCursorRef => "mouseCursor",
449        overlay_color: WidgetStatePropertyRef<Option<Color>> => "overlayColor",
450        splash_radius: f64 => "splashRadius",
451        focus_node: FocusNodeRef => "focusNode",
452        states_controller: Ref<WidgetStatesController> => "statesController",
453        on_focus_change: ValueChanged<bool> => "onFocusChange",
454        apply_cupertino_theme: bool => "applyCupertinoTheme",
455        tile_color: Color => "tileColor",
456        is_three_line: bool => "isThreeLine",
457        dense: bool => "dense",
458        content_padding: EdgeInsetsGeometry => "contentPadding",
459        control_affinity: ListTileControlAffinity => "controlAffinity",
460        shape: ShapeBorderRef => "shape",
461        selected_tile_color: Color => "selectedTileColor",
462        visual_density: VisualDensity => "visualDensity",
463        enable_feedback: bool => "enableFeedback",
464        horizontal_title_gap: f64 => "horizontalTitleGap",
465        min_vertical_padding: f64 => "minVerticalPadding",
466        min_leading_width: f64 => "minLeadingWidth",
467        min_tile_height: f64 => "minTileHeight",
468        hover_color: Color => "hoverColor",
469    );
470
471    switch_list_tile_widget_setters!(
472        title => "title",
473        subtitle => "subtitle",
474        secondary => "secondary",
475    );
476
477    /// Dart `SwitchListTile(dragStartBehavior:)`.
478    pub fn drag_start_behavior(mut self, drag_start_behavior: DragStartBehavior) -> SwitchListTile {
479        self.drag_start_behavior = drag_start_behavior;
480        self
481    }
482
483    /// Dart `SwitchListTile(autofocus:)`.
484    pub fn autofocus(mut self, autofocus: bool) -> SwitchListTile {
485        self.autofocus = autofocus;
486        self
487    }
488
489    /// Dart `SwitchListTile(internalAddSemanticForOnTap:)`.
490    pub fn internal_add_semantic_for_on_tap(
491        mut self,
492        internal_add_semantic_for_on_tap: bool,
493    ) -> SwitchListTile {
494        self.internal_add_semantic_for_on_tap = internal_add_semantic_for_on_tap;
495        self
496    }
497
498    /// Dart `SwitchListTile(selected:)`.
499    pub fn selected(mut self, selected: bool) -> SwitchListTile {
500        self.selected = selected;
501        self
502    }
503
504    /// Dart's `applyCupertinoTheme` field: what
505    /// [`apply_cupertino_theme`](Self::apply_cupertino_theme) was given, and false for a tile
506    /// made with [`SwitchListTile::new`], whose constructor sets it so.
507    pub fn effective_apply_cupertino_theme(&self) -> Option<bool> {
508        match self.switch_list_tile_type {
509            SwitchListTileType::Material => Some(false),
510            SwitchListTileType::Adaptive => self.apply_cupertino_theme,
511        }
512    }
513
514    /// The `Switch.adaptive` or `Switch` Dart's `build` puts in the control slot.
515    fn build_switch(&self) -> Switch {
516        let mut switch = match self.switch_list_tile_type {
517            SwitchListTileType::Adaptive => {
518                let mut switch = Switch::adaptive(self.value, self.on_changed.clone());
519                switch.apply_cupertino_theme = self.effective_apply_cupertino_theme();
520                switch
521            }
522            SwitchListTileType::Material => Switch::new(self.value, self.on_changed.clone()),
523        }
524        .material_tap_target_size(
525            self.material_tap_target_size
526                .unwrap_or(MaterialTapTargetSize::ShrinkWrap),
527        )
528        .autofocus(self.autofocus)
529        .drag_start_behavior(self.drag_start_behavior);
530        switch.active_color = self.active_color;
531        switch.active_thumb_color = self.active_thumb_color;
532        switch.active_track_color = self.active_track_color;
533        switch.inactive_track_color = self.inactive_track_color;
534        switch.inactive_thumb_color = self.inactive_thumb_color;
535        switch.on_focus_change = self.on_focus_change.clone();
536        switch.thumb_color = self.thumb_color.clone();
537        switch.track_color = self.track_color.clone();
538        switch.track_outline_color = self.track_outline_color.clone();
539        switch.thumb_icon = self.thumb_icon.clone();
540        switch.mouse_cursor = self.mouse_cursor.clone();
541        switch.splash_radius = self.splash_radius;
542        switch.overlay_color = self.overlay_color.clone();
543        switch
544    }
545
546    /// Dart's `onTap` closure: flips this tile's value.
547    fn handle_tap(&self) -> Option<GestureTapCallback> {
548        let on_changed = Rc::clone(self.on_changed.as_ref()?);
549        let value = self.value;
550        Some(GestureTapCallback::new(move |app: &mut App| {
551            on_changed(app, !value);
552        }))
553    }
554}
555
556impl Debug for SwitchListTile {
557    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
558        f.debug_struct("SwitchListTile")
559            .field("value", &if self.value { "on" } else { "off" })
560            .field(
561                "on_changed",
562                &if self.on_changed.is_some() {
563                    "enabled"
564                } else {
565                    "disabled"
566                },
567            )
568            .finish_non_exhaustive()
569    }
570}
571
572impl StatelessWidget for SwitchListTile {
573    fn key(&self) -> Option<&KeyRef> {
574        self.key.as_ref()
575    }
576
577    fn debug_check_constructor(&self) {
578        debug_assert!(self.is_three_line != Some(true) || self.subtitle.is_some());
579    }
580
581    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
582        let control = ExcludeFocus::new(self.build_switch()).into_widget();
583
584        let list_tile_theme = ListTileTheme::of(app, context);
585        let effective_control_affinity = self
586            .control_affinity
587            .or(list_tile_theme.control_affinity)
588            .unwrap_or(ListTileControlAffinity::Platform);
589        let (leading, trailing) = match effective_control_affinity {
590            ListTileControlAffinity::Leading => (Some(control), self.secondary.clone()),
591            ListTileControlAffinity::Trailing | ListTileControlAffinity::Platform => {
592                (self.secondary.clone(), Some(control))
593            }
594        };
595
596        let theme = Theme::of(app, context);
597        let switch_theme = SwitchTheme::of(app, context);
598        let mut states = WidgetStates::new();
599        if self.selected {
600            states.insert(WidgetState::Selected);
601        }
602        let effective_active_color = self
603            .active_thumb_color
604            .or(self.active_color)
605            .or_else(|| {
606                switch_theme
607                    .thumb_color
608                    .as_ref()
609                    .and_then(|thumb_color| thumb_color.resolve(&states))
610            })
611            .unwrap_or(theme.color_scheme.secondary());
612        let mut list_tile = ListTile::new()
613            .selected_color(effective_active_color)
614            .enabled(self.on_changed.is_some())
615            .selected(self.selected)
616            .autofocus(self.autofocus);
617        list_tile.leading = leading;
618        list_tile.title = self.title.clone();
619        list_tile.subtitle = self.subtitle.clone();
620        list_tile.trailing = trailing;
621        list_tile.is_three_line = self.is_three_line;
622        list_tile.dense = self.dense;
623        list_tile.content_padding = self.content_padding;
624        list_tile.on_tap = self.handle_tap();
625        list_tile.selected_tile_color = self.selected_tile_color;
626        list_tile.shape = self.shape.clone();
627        list_tile.tile_color = self.tile_color;
628        list_tile.visual_density = self.visual_density;
629        list_tile.focus_node = self.focus_node.clone();
630        list_tile.states_controller = self.states_controller.clone();
631        list_tile.on_focus_change = self.on_focus_change.clone();
632        list_tile.enable_feedback = self.enable_feedback;
633        list_tile.horizontal_title_gap = self.horizontal_title_gap;
634        list_tile.min_vertical_padding = self.min_vertical_padding;
635        list_tile.min_leading_width = self.min_leading_width;
636        list_tile.min_tile_height = self.min_tile_height;
637        list_tile.hover_color = self.hover_color;
638        list_tile.internal_add_semantic_for_on_tap = self.internal_add_semantic_for_on_tap;
639        MergeSemantics::new().child(list_tile).into_widget()
640    }
641}
642
643#[cfg(test)]
644mod tests {
645    use std::cell::{Cell, RefCell};
646
647    use waft_embedder::{Offset, PointerChange, Size, TargetPlatform, TextDirection};
648    use waft_painting::{AlignmentGeometry, EdgeInsets, EdgeInsetsDirectional};
649    use waft_services::SystemMouseCursors;
650    use waft_widgets::{
651        Center, Container, Directionality, FocusHighlightStrategy, GlobalKey, ListView, SizedBox,
652        StatefulBuilder, Text, WidgetStateProperty, downcast_widget,
653    };
654
655    use waft_widgets::testing::{
656        TestPointer, WidgetTester, expect, find, finds_one_widget, test_widgets,
657    };
658
659    use super::*;
660    use crate::checkbox_list_tile::tests::{
661        IS_THREE_LINE_FRAMES, check_control_is_skipped_by_traversal,
662        check_default_horizontal_title_gap, check_horizontal_title_gap_0,
663        check_horizontal_title_gap_with_visual_density, check_min_leading_width_60,
664        check_min_tile_height, check_min_vertical_padding_80, check_on_focus_change,
665        expected_three_line_rects, focus_of, has_primary_focus, ink_well_custom_border,
666        ink_well_enable_feedback, is_three_line_rects, nth, pump_in_material, pump_wrapped,
667        rect_of, right_rounded_border, text_center,
668    };
669    use crate::colors::Colors;
670    use crate::constants::K_RADIAL_REACTION_ALPHA;
671    use crate::icons::Icons;
672    use crate::list_tile::tests::{m2, m3};
673    use crate::list_tile_theme::ListTileThemeData;
674    use crate::material::Material;
675    use crate::scaffold::Scaffold;
676    use crate::switch::tests::{
677        c, circles, color_of, drawn, glyph_origins, hover, ignore, press, stroke_of, tap,
678    };
679    use crate::switch_theme::SwitchThemeData;
680    use crate::test_support::PaintInspection;
681    use crate::theme_data::ThemeData;
682    use crate::tooltip::tests::pump_app;
683
684    /// The colour of the last thing the switch draws: its thumb.
685    fn thumb(tester: &WidgetTester) -> Option<u32> {
686        drawn(tester).last().and_then(color_of)
687    }
688
689    /// The colour of the first thing the switch draws: its track.
690    fn track(tester: &WidgetTester) -> Option<u32> {
691        drawn(tester).first().and_then(color_of)
692    }
693
694    /// The colours of the outlines the switch strokes.
695    fn strokes(tester: &WidgetTester) -> Vec<u32> {
696        drawn(tester)
697            .iter()
698            .filter_map(|drawn| stroke_of(drawn).map(|(color, ..)| color))
699            .collect()
700    }
701
702    /// A tile whose value a `StatefulBuilder` keeps and whose `on_changed` sets.
703    fn stateful_tile(
704        value: &Rc<Cell<bool>>,
705        configure: impl Fn(SwitchListTile) -> SwitchListTile + 'static,
706    ) -> WidgetRef {
707        let value = Rc::clone(value);
708        StatefulBuilder::new(move |_app, _context, set_state| {
709            let value_now = Rc::clone(&value);
710            configure(SwitchListTile::new(
711                value.get(),
712                Some(Rc::new(move |app: &mut App, new_value: bool| {
713                    let value = Rc::clone(&value_now);
714                    set_state(app, &mut |_app| value.set(new_value));
715                })),
716            ))
717            .into_widget()
718        })
719        .into_widget()
720    }
721
722    /// The selected/disabled state frames: whether the tile is enabled and on.
723    const STATE_FRAMES: [(bool, bool); 4] =
724        [(false, false), (false, true), (true, false), (true, true)];
725
726    /// Dart's `getXxxColor` of the state cases: one colour per state frame.
727    fn state_colors(
728        [
729            inactive_disabled,
730            active_disabled,
731            inactive_enabled,
732            active_enabled,
733        ]: [Color; 4],
734    ) -> WidgetStatePropertyRef<Option<Color>> {
735        <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
736            Some(if states.contains(&WidgetState::Disabled) {
737                if states.contains(&WidgetState::Selected) {
738                    active_disabled
739                } else {
740                    inactive_disabled
741                }
742            } else if states.contains(&WidgetState::Selected) {
743                active_enabled
744            } else {
745                inactive_enabled
746            })
747        })
748    }
749
750    /// Dart's `getXxxColor` of the hover cases: `hovered` when hovered, else transparent.
751    fn hovered_colors(hovered: Color) -> WidgetStatePropertyRef<Option<Color>> {
752        <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
753            Some(if states.contains(&WidgetState::Hovered) {
754                hovered
755            } else {
756                Colors::TRANSPARENT
757            })
758        })
759    }
760
761    const STATE_COLORS: [Color; 4] = [
762        Color::new(0xFF000004),
763        Color::new(0xFF000002),
764        Color::new(0xFF000003),
765        Color::new(0xFF000001),
766    ];
767
768    #[test]
769    fn switch_list_tile_control_test() {
770        test_widgets(|tester| {
771            let log = Rc::new(RefCell::new(Vec::new()));
772            let on_changed: ValueChanged<bool> = {
773                let log = Rc::clone(&log);
774                Rc::new(move |_app, value| log.borrow_mut().push(Some(value)))
775            };
776            pump_wrapped(tester, |_app| {
777                SwitchListTile::new(true, Some(on_changed))
778                    .title(Text::new("Hello"))
779                    .into_widget()
780            });
781            let hello = text_center(tester, "Hello");
782            tester.tap_at(hello, 1);
783            log.borrow_mut().push(None);
784            tap(tester);
785            assert_eq!(*log.borrow(), [Some(false), None, Some(false)]);
786        });
787    }
788
789    #[test]
790    fn material2_switch_list_tile_has_the_right_colors() {
791        test_widgets(|tester| {
792            use crate::switch::tests::{M2_SHADOWS, colors};
793
794            let value = Rc::new(Cell::new(false));
795            let host = stateful_tile(&value, |tile| {
796                tile.active_color(Colors::RED.shade500())
797                    .active_track_color(Colors::GREEN.shade500())
798                    .inactive_thumb_color(Colors::YELLOW.shade500())
799                    .inactive_track_color(Colors::BLUE.shade500())
800            });
801            let root = {
802                let app = tester.cell.borrow();
803                waft_widgets::MediaQuery::new(
804                    waft_widgets::MediaQueryData::new().padding(EdgeInsets::all(8.0)),
805                    crate::theme::Theme::new(
806                        m2(&app),
807                        Directionality::new(TextDirection::Ltr, Material::new().child(host)),
808                    ),
809                )
810                .into_widget()
811            };
812            // The track, the three thumb shadows and the thumb; the transparent track outline,
813            // Dart's second `..rrect()`, is not recorded.
814            let sequence =
815                |track: Color, thumb: Color| [&[c(track)][..], &M2_SHADOWS, &[c(thumb)]].concat();
816            tester.pump_widget(root);
817            assert_eq!(
818                colors(&drawn(tester)),
819                sequence(Colors::BLUE.shade500(), Colors::YELLOW.shade500())
820            );
821
822            tap(tester);
823            tester.pump_and_settle();
824            assert_eq!(
825                colors(&drawn(tester)),
826                sequence(Colors::GREEN.shade500(), Colors::RED.shade500())
827            );
828        });
829    }
830
831    #[test]
832    fn material3_switch_list_tile_has_the_right_colors() {
833        test_widgets(|tester| {
834            let value = Rc::new(Cell::new(false));
835            let host = stateful_tile(&value, |tile| {
836                tile.active_color(Colors::RED.shade500())
837                    .active_track_color(Colors::GREEN.shade500())
838                    .inactive_thumb_color(Colors::YELLOW.shade500())
839                    .inactive_track_color(Colors::BLUE.shade500())
840            });
841            let root = {
842                let app = tester.cell.borrow();
843                waft_widgets::MediaQuery::new(
844                    waft_widgets::MediaQueryData::new().padding(EdgeInsets::all(8.0)),
845                    crate::theme::Theme::new(
846                        m3(&app),
847                        Directionality::new(TextDirection::Ltr, Material::new().child(host)),
848                    ),
849                )
850                .into_widget()
851            };
852            tester.pump_widget(root);
853            assert_eq!(track(tester), Some(c(Colors::BLUE.shade500())));
854            assert_eq!(thumb(tester), Some(c(Colors::YELLOW.shade500())));
855
856            tap(tester);
857            tester.pump_and_settle();
858            assert_eq!(track(tester), Some(c(Colors::GREEN.shade500())));
859            assert_eq!(thumb(tester), Some(c(Colors::RED.shade500())));
860        });
861    }
862
863    #[test]
864    fn switch_list_tile_adaptive_only_uses_material_switch() {
865        test_widgets(|tester| {
866            let value = Rc::new(Cell::new(false));
867            for platform in [
868                TargetPlatform::IOS,
869                TargetPlatform::MacOS,
870                TargetPlatform::Android,
871                TargetPlatform::Fuchsia,
872                TargetPlatform::Linux,
873                TargetPlatform::Windows,
874            ] {
875                value.set(false);
876                let host = {
877                    let value = Rc::clone(&value);
878                    StatefulBuilder::new(move |_app, _context, set_state| {
879                        let value_now = Rc::clone(&value);
880                        Material::new()
881                            .child(Center::new().child(SwitchListTile::adaptive(
882                                value.get(),
883                                Some(Rc::new(move |app: &mut App, new_value: bool| {
884                                    let value = Rc::clone(&value_now);
885                                    set_state(app, &mut |_app| value.set(new_value));
886                                })),
887                            )))
888                            .into_widget()
889                    })
890                    .into_widget()
891                };
892                pump_app(
893                    tester,
894                    move |app| ThemeData::builder().platform(platform).build(app),
895                    |_app| host,
896                );
897                assert!(
898                    find::by_type::<waft_cupertino::CupertinoSwitch>()
899                        .evaluate(tester)
900                        .is_empty()
901                );
902                expect(tester, &find::by_type::<Switch>(), finds_one_widget());
903                assert!(!value.get(), "on {platform:?}");
904
905                let at = rect_of::<SwitchListTile>(tester, 0).center();
906                tester.tap_at(at, 1);
907                assert!(value.get(), "on {platform:?}");
908            }
909        });
910    }
911
912    #[test]
913    fn switch_list_tile_content_padding() {
914        test_widgets(|tester| {
915            let frame = |tester: &mut WidgetTester, text_direction: TextDirection| {
916                let theme = m3(&tester.cell.borrow());
917                tester.pump_widget(crate::list_tile::tests::bare(
918                    theme,
919                    Directionality::new(
920                        text_direction,
921                        Material::new().child(
922                            Container::new()
923                                .alignment(AlignmentGeometry::TOP_LEFT)
924                                .child(
925                                    SwitchListTile::new(true, ignore())
926                                        .content_padding(EdgeInsetsDirectional::only(
927                                            10.0, 30.0, 20.0, 40.0,
928                                        ))
929                                        .secondary(Text::new("L"))
930                                        .title(Text::new("title")),
931                                ),
932                        ),
933                    ),
934                ));
935            };
936
937            frame(tester, TextDirection::Ltr);
938            assert_eq!(tester.get_rect(find::text("L")).left, 10.0); // contentPadding.start = 10
939            assert_eq!(rect_of::<Switch>(tester, 0).right, 780.0); // 800 - contentPadding.end
940
941            frame(tester, TextDirection::Rtl);
942            assert_eq!(rect_of::<Switch>(tester, 0).left, 20.0); // contentPadding.end = 20
943            assert_eq!(tester.get_rect(find::text("L")).right, 790.0); // 800 - contentPadding.start
944        });
945    }
946
947    #[test]
948    fn switch_list_tile_forwards_states_controller_to_list_tile() {
949        test_widgets(|tester| {
950            let controller = WidgetStatesController::new(&mut tester.cell.borrow_mut(), None);
951            pump_in_material(tester, m3, |_app| {
952                ListView::new()
953                    .children([SwitchListTile::new(true, ignore())
954                        .title(Text::new("Switch"))
955                        .states_controller(controller.clone())
956                        .into_widget()])
957                    .into_widget()
958            });
959            let forwarded = tester.widget(nth::<ListTile>(tester, 0), |tile: &ListTile| {
960                tile.states_controller.clone()
961            });
962            assert_eq!(forwarded, Some(controller));
963        });
964    }
965
966    #[test]
967    fn switch_list_tile_can_autofocus_unless_disabled() {
968        test_widgets(|tester| {
969            let child_key = GlobalKey::new();
970            for (on_changed, focused) in [(ignore(), true), (None, false)] {
971                let key = child_key.clone();
972                pump_in_material(tester, m3, move |_app| {
973                    ListView::new()
974                        .children([SwitchListTile::new(true, on_changed)
975                            .title(Text::new("A").key(key.into()))
976                            .autofocus(true)
977                            .into_widget()])
978                        .into_widget()
979                });
980                tester.pump();
981                let node = focus_of(tester, &child_key);
982                assert_eq!(has_primary_focus(tester, node), focused);
983            }
984        });
985    }
986
987    /// The `leading` and `trailing` of the tile's `ListTile`.
988    fn slots(tester: &WidgetTester) -> (Option<WidgetRef>, Option<WidgetRef>) {
989        tester.widget(nth::<ListTile>(tester, 0), |tile: &ListTile| {
990            (tile.leading.clone(), tile.trailing.clone())
991        })
992    }
993
994    /// Whether `slot` is an `ExcludeFocus` around a `Switch`.
995    fn is_excluded_switch(slot: &Option<WidgetRef>) -> bool {
996        slot.as_ref()
997            .and_then(|slot| downcast_widget::<ExcludeFocus>(&**slot))
998            .is_some_and(|exclude_focus| downcast_widget::<Switch>(&*exclude_focus.child).is_some())
999    }
1000
1001    fn is_icon(slot: &Option<WidgetRef>) -> bool {
1002        slot.as_ref()
1003            .is_some_and(|slot| downcast_widget::<Icon>(&**slot).is_some())
1004    }
1005
1006    fn info_tile() -> SwitchListTile {
1007        SwitchListTile::new(true, None)
1008            .secondary(Icon::new(Some(Icons::info())))
1009            .title(Text::new("Title"))
1010    }
1011
1012    #[test]
1013    fn switch_list_tile_control_affinity_test() {
1014        test_widgets(|tester| {
1015            pump_in_material(tester, m3, |_app| {
1016                info_tile()
1017                    .control_affinity(ListTileControlAffinity::Leading)
1018                    .into_widget()
1019            });
1020            // When controlAffinity is ListTileControlAffinity.leading, the position of
1021            // Switch is at leading edge and SwitchListTile.secondary at trailing edge.
1022            let (leading, trailing) = slots(tester);
1023            assert!(is_excluded_switch(&leading));
1024            assert!(is_icon(&trailing));
1025        });
1026    }
1027
1028    #[test]
1029    fn switch_list_tile_control_affinity_default_value_test() {
1030        test_widgets(|tester| {
1031            pump_in_material(tester, m3, |_app| info_tile().into_widget());
1032            // By default, value of controlAffinity is ListTileControlAffinity.platform,
1033            // where the position of SwitchListTile.secondary is at leading edge and Switch
1034            // at trailing edge. This also covers test for ListTileControlAffinity.trailing.
1035            let (leading, trailing) = slots(tester);
1036            assert!(is_excluded_switch(&trailing));
1037            assert!(is_icon(&leading));
1038        });
1039    }
1040
1041    #[test]
1042    fn switch_list_tile_respects_shape() {
1043        test_widgets(|tester| {
1044            pump_in_material(tester, m3, |_app| {
1045                SwitchListTile::new(true, None)
1046                    .title(Text::new("Title"))
1047                    .shape(ShapeBorderRef::new(right_rounded_border()))
1048                    .into_widget()
1049            });
1050            let shape: ShapeBorderRef = ShapeBorderRef::new(right_rounded_border());
1051            assert!(ink_well_custom_border(tester).as_deref() == Some(&*shape));
1052        });
1053    }
1054
1055    #[test]
1056    fn switch_list_tile_respects_tile_color() {
1057        test_widgets(|tester| {
1058            let tile_color = Colors::RED.shade500();
1059            pump_wrapped(tester, |_app| {
1060                Center::new()
1061                    .child(
1062                        SwitchListTile::new(false, None)
1063                            .title(Text::new("Title"))
1064                            .tile_color(tile_color),
1065                    )
1066                    .into_widget()
1067            });
1068            waft_rendering::testing::assert_paints(
1069                tester.ink_list().ops(),
1070                &[waft_rendering::testing::PaintCall::rect(Some(tile_color))],
1071            );
1072        });
1073    }
1074
1075    #[test]
1076    fn switch_list_tile_respects_selected_tile_color() {
1077        test_widgets(|tester| {
1078            let selected_tile_color = Colors::GREEN.shade500();
1079            pump_wrapped(tester, |_app| {
1080                Center::new()
1081                    .child(
1082                        SwitchListTile::new(false, None)
1083                            .title(Text::new("Title"))
1084                            .selected(true)
1085                            .selected_tile_color(selected_tile_color),
1086                    )
1087                    .into_widget()
1088            });
1089            waft_rendering::testing::assert_paints(
1090                tester.ink_list().ops(),
1091                &[waft_rendering::testing::PaintCall::rect(Some(
1092                    selected_tile_color,
1093                ))],
1094            );
1095        });
1096    }
1097
1098    #[test]
1099    fn switch_list_tile_selected_item_text_color() {
1100        test_widgets(|tester| {
1101            // Regression test for https://github.com/flutter/flutter/pull/76909
1102            const ACTIVE_COLOR: Color = Color::new(0xff00ff00);
1103            // Dart pumps the same frame twice, `activeColor` given and `thumbColor` not.
1104            for _ in 0..2 {
1105                pump_app(
1106                    tester,
1107                    |app| {
1108                        ThemeData::builder()
1109                            .switch_theme(SwitchThemeData::new().thumb_color(
1110                                <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|_| None),
1111                            ))
1112                            .build(app)
1113                    },
1114                    |_app| {
1115                        Scaffold::new()
1116                            .body(
1117                                Center::new().child(
1118                                    SwitchListTile::new(true, ignore())
1119                                        .active_color(ACTIVE_COLOR)
1120                                        .selected(true)
1121                                        .title(Text::new("title")),
1122                                ),
1123                            )
1124                            .into_widget()
1125                    },
1126                );
1127                assert_eq!(tester.text_color("title"), ACTIVE_COLOR);
1128            }
1129        });
1130    }
1131
1132    #[test]
1133    fn switch_list_tile_respects_visual_density() {
1134        test_widgets(|tester| {
1135            pump_wrapped(tester, |_app| {
1136                Center::new()
1137                    .child(
1138                        SwitchListTile::new(false, ignore())
1139                            .autofocus(true)
1140                            .visual_density(VisualDensity::STANDARD),
1141                    )
1142                    .into_widget()
1143            });
1144            tester.pump_and_settle();
1145            assert_eq!(
1146                rect_of::<SwitchListTile>(tester, 0).size(),
1147                Size::new(800.0, 56.0)
1148            );
1149        });
1150    }
1151
1152    #[test]
1153    fn switch_list_tile_respects_focus_node() {
1154        test_widgets(|tester| {
1155            let child_key = GlobalKey::new();
1156            let key = child_key.clone();
1157            pump_wrapped(tester, move |_app| {
1158                Center::new()
1159                    .child(
1160                        SwitchListTile::new(false, ignore()).title(Text::new("A").key(key.into())),
1161                    )
1162                    .into_widget()
1163            });
1164            tester.pump();
1165            let tile_node = focus_of(tester, &child_key);
1166            tile_node.request_focus(&mut tester.cell.borrow_mut(), None);
1167            tester.pump(); // Let the focus take effect.
1168            let node = focus_of(tester, &child_key);
1169            assert!(has_primary_focus(tester, node));
1170            assert!(has_primary_focus(tester, tile_node));
1171        });
1172    }
1173
1174    #[test]
1175    fn switch_list_tile_on_focus_change_callback() {
1176        test_widgets(|tester| {
1177            check_on_focus_change(tester, |node, on_focus_change| {
1178                SwitchListTile::new(true, ignore())
1179                    .focus_node(node)
1180                    .on_focus_change(on_focus_change)
1181                    .into_widget()
1182            });
1183        });
1184    }
1185
1186    #[test]
1187    fn switch_list_tile_adaptive_on_focus_change_callback() {
1188        test_widgets(|tester| {
1189            check_on_focus_change(tester, |node, on_focus_change| {
1190                SwitchListTile::adaptive(true, ignore())
1191                    .focus_node(node)
1192                    .on_focus_change(on_focus_change)
1193                    .into_widget()
1194            });
1195        });
1196    }
1197
1198    #[test]
1199    fn switch_list_tile_respects_enable_feedback() {
1200        test_widgets(|tester| {
1201            for enable_feedback in [false, true] {
1202                pump_wrapped(tester, |_app| {
1203                    Center::new()
1204                        .child(
1205                            SwitchListTile::new(false, ignore()).enable_feedback(enable_feedback),
1206                        )
1207                        .into_widget()
1208                });
1209                assert_eq!(ink_well_enable_feedback(tester), enable_feedback);
1210            }
1211        });
1212    }
1213
1214    #[test]
1215    fn switch_list_tile_respects_hover_color() {
1216        test_widgets(|tester| {
1217            let key = GlobalKey::new();
1218            let orange = Colors::ORANGE.shade500();
1219            let tile_key = key.clone();
1220            pump_wrapped(tester, move |_app| {
1221                Center::new()
1222                    .child(
1223                        SizedBox::new().width(500.0).height(100.0).child(
1224                            Material::new().color(Colors::WHITE).child(
1225                                SwitchListTile::new(false, ignore())
1226                                    .key(tile_key.into())
1227                                    .hover_color(orange)
1228                                    .title(Text::new("A")),
1229                            ),
1230                        ),
1231                    )
1232                    .into_widget()
1233            });
1234
1235            // Start hovering
1236            let mut gesture = TestPointer::mouse(1, 0);
1237            let center = tester.get_center(&key);
1238            tester.add_pointer(&mut gesture, center);
1239            tester.pump();
1240            tester.pump_and_settle();
1241            // Dart's `Material.of(tester.element(find.byKey(key)))`: the white material, inside
1242            // the one `wrap` gives.
1243            let materials = tester.all::<crate::material::RenderInkFeatures>();
1244            let mut canvas = waft_embedder::Canvas::new();
1245            materials[1].paint_ink_features(
1246                &mut tester.cell.borrow_mut(),
1247                &mut canvas,
1248                Offset::ZERO,
1249            );
1250            waft_rendering::testing::assert_paints(
1251                canvas.build().ops(),
1252                &[waft_rendering::testing::PaintCall::rect_at(
1253                    waft_embedder::Rect::from_ltrb(0.0, 0.0, 500.0, 100.0),
1254                    Some(orange),
1255                )],
1256            );
1257            tester.send(&gesture, PointerChange::Remove);
1258        });
1259    }
1260
1261    #[test]
1262    fn material2_switch_list_tile_respects_thumb_color_in_active_enabled_states() {
1263        test_widgets(|tester| {
1264            let thumb_color = state_colors(STATE_COLORS);
1265            for ((enabled, selected), expected) in STATE_FRAMES.into_iter().zip(STATE_COLORS) {
1266                let thumb_color = Rc::clone(&thumb_color);
1267                pump_in_material(tester, m2, move |_app| {
1268                    SwitchListTile::new(selected, if enabled { ignore() } else { None })
1269                        .thumb_color(thumb_color)
1270                        .into_widget()
1271                });
1272                tester.pump_and_settle();
1273                assert_eq!(thumb(tester), Some(c(expected)), "{enabled} {selected}");
1274            }
1275        });
1276    }
1277
1278    #[test]
1279    fn material3_switch_list_tile_respects_thumb_color_in_active_enabled_states() {
1280        test_widgets(|tester| {
1281            let thumb_color = state_colors(STATE_COLORS);
1282            for ((enabled, selected), expected) in STATE_FRAMES.into_iter().zip(STATE_COLORS) {
1283                let thumb_color = Rc::clone(&thumb_color);
1284                pump_in_material(tester, m3, move |_app| {
1285                    SwitchListTile::new(selected, if enabled { ignore() } else { None })
1286                        .thumb_color(thumb_color)
1287                        .into_widget()
1288                });
1289                tester.pump_and_settle();
1290                assert_eq!(thumb(tester), Some(c(expected)), "{enabled} {selected}");
1291            }
1292        });
1293    }
1294
1295    #[test]
1296    fn material2_switch_list_tile_respects_thumb_color_in_hovered_pressed_states() {
1297        test_widgets(|tester| {
1298            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1299            const HOVERED_THUMB_COLOR: Color = Color::new(0xFF4CAF50);
1300            const PRESSED_THUMB_COLOR: Color = Color::new(0xFFF44336);
1301            let thumb_color = <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
1302                Some(if states.contains(&WidgetState::Pressed) {
1303                    PRESSED_THUMB_COLOR
1304                } else if states.contains(&WidgetState::Hovered) {
1305                    HOVERED_THUMB_COLOR
1306                } else {
1307                    Colors::TRANSPARENT
1308                })
1309            });
1310            pump_in_material(tester, m2, |_app| {
1311                SwitchListTile::new(false, ignore())
1312                    .thumb_color(thumb_color)
1313                    .into_widget()
1314            });
1315            tester.pump_and_settle();
1316
1317            // Start hovering
1318            let gesture = hover(tester);
1319            tester.pump_and_settle();
1320            assert_eq!(thumb(tester), Some(c(HOVERED_THUMB_COLOR)));
1321
1322            // On pressed state
1323            let touch = press(tester);
1324            tester.pump_and_settle();
1325            assert_eq!(thumb(tester), Some(c(PRESSED_THUMB_COLOR)));
1326            tester.up(&touch);
1327            tester.send(&gesture, PointerChange::Remove);
1328        });
1329    }
1330
1331    #[test]
1332    fn material3_switch_list_tile_respects_thumb_color_in_hovered_pressed_states() {
1333        test_widgets(|tester| {
1334            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1335            const HOVERED_THUMB_COLOR: Color = Color::new(0xFF4CAF50);
1336            const PRESSED_THUMB_COLOR: Color = Color::new(0xFFF44336);
1337            let thumb_color = <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
1338                Some(if states.contains(&WidgetState::Pressed) {
1339                    PRESSED_THUMB_COLOR
1340                } else if states.contains(&WidgetState::Hovered) {
1341                    HOVERED_THUMB_COLOR
1342                } else {
1343                    Colors::TRANSPARENT
1344                })
1345            });
1346            pump_in_material(tester, m3, |_app| {
1347                SwitchListTile::new(false, ignore())
1348                    .thumb_color(thumb_color)
1349                    .into_widget()
1350            });
1351            tester.pump_and_settle();
1352
1353            // Start hovering
1354            let gesture = hover(tester);
1355            tester.pump_and_settle();
1356            assert_eq!(thumb(tester), Some(c(HOVERED_THUMB_COLOR)));
1357
1358            // On pressed state
1359            let touch = press(tester);
1360            tester.pump_and_settle();
1361            assert_eq!(thumb(tester), Some(c(PRESSED_THUMB_COLOR)));
1362            tester.up(&touch);
1363            tester.send(&gesture, PointerChange::Remove);
1364        });
1365    }
1366
1367    #[test]
1368    fn switch_list_tile_respects_track_color_in_active_enabled_states() {
1369        test_widgets(|tester| {
1370            let track_color = state_colors(STATE_COLORS);
1371            for (index, ((enabled, selected), expected)) in
1372                STATE_FRAMES.into_iter().zip(STATE_COLORS).enumerate()
1373            {
1374                let track_color = Rc::clone(&track_color);
1375                pump_wrapped(tester, move |_app| {
1376                    SwitchListTile::new(selected, if enabled { ignore() } else { None })
1377                        .track_color(track_color)
1378                        .into_widget()
1379                });
1380                if index > 0 {
1381                    tester.pump_and_settle();
1382                }
1383                assert_eq!(track(tester), Some(c(expected)), "{enabled} {selected}");
1384            }
1385        });
1386    }
1387
1388    #[test]
1389    fn switch_list_tile_respects_track_color_in_hovered_states() {
1390        test_widgets(|tester| {
1391            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1392            const HOVERED_TRACK_COLOR: Color = Color::new(0xFF4CAF50);
1393            pump_wrapped(tester, |_app| {
1394                SwitchListTile::new(false, ignore())
1395                    .track_color(hovered_colors(HOVERED_TRACK_COLOR))
1396                    .into_widget()
1397            });
1398            tester.pump_and_settle();
1399
1400            // Start hovering
1401            let gesture = hover(tester);
1402            tester.pump_and_settle();
1403            assert_eq!(track(tester), Some(c(HOVERED_TRACK_COLOR)));
1404            tester.send(&gesture, PointerChange::Remove);
1405        });
1406    }
1407
1408    #[test]
1409    fn switch_list_tile_respects_thumb_icon_m3() {
1410        test_widgets(|tester| {
1411            crate::icons::install_material_icon_font(&mut tester.cell.borrow_mut());
1412            let active_icon = Rc::new(Icon::new(Some(Icons::check())));
1413            let inactive_icon = Rc::new(Icon::new(Some(Icons::close())));
1414            let thumb_icon = |active_icon: Option<Rc<Icon>>, inactive_icon: Option<Rc<Icon>>| {
1415                <dyn WidgetStateProperty<Option<Rc<Icon>>>>::resolve_with(move |states| {
1416                    if states.contains(&WidgetState::Selected) {
1417                        return active_icon.clone();
1418                    }
1419                    inactive_icon.clone()
1420                })
1421            };
1422            let frame = |tester: &mut WidgetTester,
1423                         active: bool,
1424                         active_icon: Option<Rc<Icon>>,
1425                         inactive_icon: Option<Rc<Icon>>| {
1426                let thumb_icon = thumb_icon(active_icon, inactive_icon);
1427                pump_app(tester, m3, |app| {
1428                    let theme = m3(app);
1429                    crate::list_tile::tests::bare(
1430                        theme,
1431                        Material::new()
1432                            .child(SwitchListTile::new(active, ignore()).thumb_icon(thumb_icon)),
1433                    )
1434                });
1435                tester.pump_and_settle();
1436                let resolved = |states: &WidgetStates| {
1437                    tester.widget(nth::<Switch>(tester, 0), |switch: &Switch| {
1438                        switch
1439                            .thumb_icon
1440                            .as_ref()
1441                            .and_then(|thumb_icon| thumb_icon.resolve(states))
1442                    })
1443                };
1444                let selected: WidgetStates = [WidgetState::Selected].into_iter().collect();
1445                let glyphs: Vec<(f64, f64)> = glyph_origins(&drawn(tester));
1446                (resolved(&selected), resolved(&WidgetStates::new()), glyphs)
1447            };
1448            // The glyph's ink is inside the 16x16 icon square Dart paints its paragraph at.
1449            let inside = |glyphs: &[(f64, f64)], left: f64, top: f64| matches!(glyphs, [(x, y)] if *x >= left && *x < left + 16.0 && *y >= top && *y < top + 16.0);
1450            let same = |icon: Option<Rc<Icon>>, expected: &Rc<Icon>| {
1451                icon.is_some_and(|icon| Rc::ptr_eq(&icon, expected))
1452            };
1453
1454            // active icon shows when switch is on.
1455            let (selected, _, glyphs) = frame(tester, true, Some(Rc::clone(&active_icon)), None);
1456            assert!(same(selected, &active_icon));
1457            assert!(inside(&glyphs, 32.0, 12.0), "{glyphs:?}");
1458
1459            // inactive icon shows when switch is off.
1460            let (_, unselected, glyphs) =
1461                frame(tester, false, None, Some(Rc::clone(&inactive_icon)));
1462            assert!(same(unselected, &inactive_icon));
1463            assert!(inside(&glyphs, 12.0, 12.0), "{glyphs:?}");
1464
1465            // active icon doesn't show when switch is off.
1466            let (selected, _, glyphs) = frame(tester, false, Some(Rc::clone(&active_icon)), None);
1467            assert!(same(selected, &active_icon));
1468            assert_eq!(glyphs, []);
1469
1470            // inactive icon doesn't show when switch is on.
1471            let (_, unselected, glyphs) =
1472                frame(tester, true, None, Some(Rc::clone(&inactive_icon)));
1473            assert!(same(unselected, &inactive_icon));
1474            assert_eq!(glyphs, []);
1475
1476            // without icon
1477            let (_, _, glyphs) = frame(tester, false, None, None);
1478            assert_eq!(glyphs, []);
1479        });
1480    }
1481
1482    fn check_material_tap_target_size(
1483        tester: &mut WidgetTester,
1484        theme: fn(&App) -> ThemeData,
1485        width: f64,
1486    ) {
1487        for (size, height) in [
1488            (MaterialTapTargetSize::Padded, 48.0),
1489            (MaterialTapTargetSize::ShrinkWrap, 40.0),
1490        ] {
1491            pump_in_material(tester, theme, move |_app| {
1492                SwitchListTile::new(false, ignore())
1493                    .material_tap_target_size(size)
1494                    .into_widget()
1495            });
1496            let given = tester.widget(nth::<Switch>(tester, 0), |switch: &Switch| {
1497                switch.material_tap_target_size
1498            });
1499            assert_eq!(given, Some(size));
1500            assert_eq!(
1501                rect_of::<Switch>(tester, 0).size(),
1502                Size::new(width, height)
1503            );
1504        }
1505    }
1506
1507    #[test]
1508    fn material2_switch_list_tile_respects_material_tap_target_size() {
1509        test_widgets(|tester| check_material_tap_target_size(tester, m2, 59.0));
1510    }
1511
1512    #[test]
1513    fn material3_switch_list_tile_respects_material_tap_target_size() {
1514        test_widgets(|tester| check_material_tap_target_size(tester, m3, 60.0));
1515    }
1516
1517    #[test]
1518    fn material2_switch_list_tile_adaptive_respects_apply_cupertino_theme() {
1519        test_widgets(|tester| {
1520            for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
1521                for (apply_cupertino_theme, expected) in
1522                    [(true, 0xFF2196F3_u32), (false, 0xFF34C759)]
1523                {
1524                    pump_in_material(
1525                        tester,
1526                        move |app| {
1527                            ThemeData::builder()
1528                                .use_material3(false)
1529                                .platform(platform)
1530                                .build(app)
1531                        },
1532                        move |_app| {
1533                            SwitchListTile::adaptive(true, ignore())
1534                                .apply_cupertino_theme(apply_cupertino_theme)
1535                                .into_widget()
1536                        },
1537                    );
1538                    tester.pump_and_settle();
1539                    expect(tester, &find::by_type::<Switch>(), finds_one_widget());
1540                    assert!(
1541                        drawn(tester)
1542                            .iter()
1543                            .any(|drawn| color_of(drawn) == Some(expected)),
1544                        "{platform:?} {apply_cupertino_theme}: {:?}",
1545                        drawn(tester)
1546                    );
1547                }
1548            }
1549        });
1550    }
1551
1552    #[test]
1553    fn material3_switch_list_tile_adaptive_respects_apply_cupertino_theme() {
1554        test_widgets(|tester| {
1555            for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
1556                for (apply_cupertino_theme, expected) in
1557                    [(true, 0xFF6750A4_u32), (false, 0xFF34C759)]
1558                {
1559                    pump_in_material(
1560                        tester,
1561                        move |app| ThemeData::builder().platform(platform).build(app),
1562                        move |_app| {
1563                            SwitchListTile::adaptive(true, ignore())
1564                                .apply_cupertino_theme(apply_cupertino_theme)
1565                                .into_widget()
1566                        },
1567                    );
1568                    tester.pump_and_settle();
1569                    expect(tester, &find::by_type::<Switch>(), finds_one_widget());
1570                    assert!(
1571                        drawn(tester)
1572                            .iter()
1573                            .any(|drawn| color_of(drawn) == Some(expected)),
1574                        "{platform:?} {apply_cupertino_theme}: {:?}",
1575                        drawn(tester)
1576                    );
1577                }
1578            }
1579        });
1580    }
1581
1582    #[test]
1583    fn switch_list_tile_passes_the_value_of_drag_start_behavior_to_switch() {
1584        test_widgets(|tester| {
1585            for drag_start_behavior in [DragStartBehavior::Start, DragStartBehavior::Down] {
1586                pump_wrapped(tester, move |_app| {
1587                    SwitchListTile::new(false, ignore())
1588                        .drag_start_behavior(drag_start_behavior)
1589                        .into_widget()
1590                });
1591                let given = tester.widget(nth::<Switch>(tester, 0), |switch: &Switch| {
1592                    switch.drag_start_behavior
1593                });
1594                assert_eq!(given, drag_start_behavior);
1595            }
1596        });
1597    }
1598
1599    #[test]
1600    fn switch_on_switch_list_tile_changes_mouse_cursor_when_hovered() {
1601        test_widgets(|tester| {
1602            // Test SwitchListTile.adaptive() constructor
1603            pump_wrapped(tester, |_app| {
1604                SwitchListTile::adaptive(false, ignore())
1605                    .mouse_cursor(MouseCursorRef::from(SystemMouseCursors::TEXT))
1606                    .into_widget()
1607            });
1608            let mut gesture = TestPointer::mouse(1, 0);
1609            let center = rect_of::<Switch>(tester, 0).center();
1610            tester.add_pointer(&mut gesture, center);
1611            tester.pump();
1612            assert_eq!(tester.active_cursor(1), SystemMouseCursors::TEXT.into());
1613
1614            // Test SwitchListTile() constructor
1615            pump_wrapped(tester, |_app| {
1616                SwitchListTile::new(false, ignore())
1617                    .mouse_cursor(MouseCursorRef::from(SystemMouseCursors::FORBIDDEN))
1618                    .into_widget()
1619            });
1620            let center = rect_of::<Switch>(tester, 0).center();
1621            tester.move_to(&mut gesture, center, false);
1622            assert_eq!(
1623                tester.active_cursor(1),
1624                SystemMouseCursors::FORBIDDEN.into()
1625            );
1626
1627            // Test default cursor
1628            pump_wrapped(tester, |_app| {
1629                SwitchListTile::new(false, ignore()).into_widget()
1630            });
1631            assert_eq!(tester.active_cursor(1), SystemMouseCursors::CLICK.into());
1632
1633            // Test default cursor when disabled
1634            pump_wrapped(tester, |_app| {
1635                SwitchListTile::new(false, None).into_widget()
1636            });
1637            assert_eq!(tester.active_cursor(1), SystemMouseCursors::BASIC.into());
1638            tester.send(&gesture, PointerChange::Remove);
1639        });
1640    }
1641
1642    #[test]
1643    fn switch_with_splash_radius_set() {
1644        test_widgets(|tester| {
1645            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1646            const SPLASH_RADIUS: f64 = 35.0;
1647            pump_wrapped(tester, |_app| {
1648                SwitchListTile::new(false, ignore())
1649                    .splash_radius(SPLASH_RADIUS)
1650                    .into_widget()
1651            });
1652            tester.pump_and_settle();
1653            let gesture = hover(tester);
1654            tester.pump_and_settle();
1655            assert!(!circles(&drawn(tester), SPLASH_RADIUS).is_empty());
1656            tester.send(&gesture, PointerChange::Remove);
1657        });
1658    }
1659
1660    #[test]
1661    fn the_overlay_color_for_the_thumb_of_the_switch_resolves_in_active_pressed_hovered_states() {
1662        test_widgets(|tester| {
1663            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1664            const ACTIVE_THUMB_COLOR: Color = Color::new(0xFF000000);
1665            const INACTIVE_THUMB_COLOR: Color = Color::new(0xFF000010);
1666            const ACTIVE_PRESSED_OVERLAY_COLOR: Color = Color::new(0xFF000001);
1667            const INACTIVE_PRESSED_OVERLAY_COLOR: Color = Color::new(0xFF000002);
1668            const HOVER_OVERLAY_COLOR: Color = Color::new(0xFF000003);
1669            const HOVER_COLOR: Color = Color::new(0xFF000005);
1670            let frame = |tester: &mut WidgetTester, active: bool, use_overlay: bool| {
1671                pump_app(tester, m3, move |_app| {
1672                    let mut tile = SwitchListTile::new(active, ignore())
1673                        .thumb_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
1674                            |states| {
1675                                Some(if states.contains(&WidgetState::Selected) {
1676                                    ACTIVE_THUMB_COLOR
1677                                } else {
1678                                    INACTIVE_THUMB_COLOR
1679                                })
1680                            },
1681                        ))
1682                        .hover_color(HOVER_COLOR);
1683                    if use_overlay {
1684                        tile = tile.overlay_color(
1685                            <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
1686                                if states.contains(&WidgetState::Pressed) {
1687                                    if states.contains(&WidgetState::Selected) {
1688                                        return Some(ACTIVE_PRESSED_OVERLAY_COLOR);
1689                                    }
1690                                    return Some(INACTIVE_PRESSED_OVERLAY_COLOR);
1691                                }
1692                                if states.contains(&WidgetState::Hovered) {
1693                                    return Some(HOVER_OVERLAY_COLOR);
1694                                }
1695                                None
1696                            }),
1697                        );
1698                    }
1699                    Scaffold::new().body(tile).into_widget()
1700                });
1701            };
1702            for (active, use_overlay, expected) in [
1703                (
1704                    false,
1705                    false,
1706                    INACTIVE_THUMB_COLOR.with_alpha(K_RADIAL_REACTION_ALPHA),
1707                ),
1708                (
1709                    true,
1710                    false,
1711                    ACTIVE_THUMB_COLOR.with_alpha(K_RADIAL_REACTION_ALPHA),
1712                ),
1713                (false, true, INACTIVE_PRESSED_OVERLAY_COLOR),
1714                (true, true, ACTIVE_PRESSED_OVERLAY_COLOR),
1715            ] {
1716                frame(tester, active, use_overlay);
1717                let touch = press(tester);
1718                tester.pump_and_settle();
1719                assert_eq!(
1720                    circles(&drawn(tester), crate::constants::K_RADIAL_REACTION_RADIUS),
1721                    [c(expected)],
1722                    "active {active}, overlay {use_overlay}"
1723                );
1724                tester.up(&touch);
1725                tester.pump_and_settle();
1726            }
1727
1728            frame(tester, false, true);
1729            tester.pump_and_settle();
1730
1731            // Start hovering
1732            let gesture = hover(tester);
1733            tester.pump_and_settle();
1734            assert_eq!(
1735                circles(&drawn(tester), crate::constants::K_RADIAL_REACTION_RADIUS),
1736                [c(HOVER_OVERLAY_COLOR)]
1737            );
1738            tester.send(&gesture, PointerChange::Remove);
1739        });
1740    }
1741
1742    #[test]
1743    fn switch_list_tile_respects_track_outline_color_in_active_enabled_states() {
1744        test_widgets(|tester| {
1745            let track_outline_color = state_colors(STATE_COLORS);
1746            for ((enabled, selected), expected) in STATE_FRAMES.into_iter().zip(STATE_COLORS) {
1747                let track_outline_color = Rc::clone(&track_outline_color);
1748                pump_wrapped(tester, move |_app| {
1749                    SwitchListTile::new(selected, if enabled { ignore() } else { None })
1750                        .track_outline_color(track_outline_color)
1751                        .into_widget()
1752                });
1753                tester.pump_and_settle();
1754                assert!(
1755                    drawn(tester)
1756                        .first()
1757                        .is_some_and(|op| stroke_of(op).is_none() && color_of(op).is_some())
1758                );
1759                assert_eq!(strokes(tester), [c(expected)], "{enabled} {selected}");
1760            }
1761        });
1762    }
1763
1764    #[test]
1765    fn switch_list_tile_respects_track_outline_color_in_hovered_state() {
1766        test_widgets(|tester| {
1767            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1768            const HOVERED_TRACK_COLOR: Color = Color::new(0xFF4CAF50);
1769            pump_wrapped(tester, |_app| {
1770                SwitchListTile::new(false, ignore())
1771                    .track_outline_color(hovered_colors(HOVERED_TRACK_COLOR))
1772                    .into_widget()
1773            });
1774            tester.pump_and_settle();
1775
1776            // Start hovering
1777            let gesture = hover(tester);
1778            tester.pump_and_settle();
1779            assert_eq!(strokes(tester), [c(HOVERED_TRACK_COLOR)]);
1780            tester.send(&gesture, PointerChange::Remove);
1781        });
1782    }
1783
1784    #[test]
1785    fn switch_list_tile_control_widget_should_not_request_focus_on_traversal() {
1786        test_widgets(|tester| {
1787            check_control_is_skipped_by_traversal(tester, |title| {
1788                let mut tile = SwitchListTile::new(true, ignore());
1789                tile.title = Some(title);
1790                tile.into_widget()
1791            });
1792        });
1793    }
1794
1795    #[test]
1796    fn switch_list_tile_uses_list_tile_theme_control_affinity() {
1797        test_widgets(|tester| {
1798            for (control_affinity, expected) in [
1799                (ListTileControlAffinity::Leading, Offset::new(92.0, 16.0)),
1800                (ListTileControlAffinity::Trailing, Offset::new(16.0, 16.0)),
1801                (ListTileControlAffinity::Platform, Offset::new(16.0, 16.0)),
1802            ] {
1803                pump_in_material(tester, m3, |_app| {
1804                    ListTileTheme::new(
1805                        SwitchListTile::new(true, ignore()).title(Text::new("SwitchListTile")),
1806                    )
1807                    .data(ListTileThemeData::new().control_affinity(control_affinity))
1808                    .into_widget()
1809                });
1810                assert_eq!(
1811                    tester.get_rect(find::text("SwitchListTile")).top_left(),
1812                    expected
1813                );
1814            }
1815        });
1816    }
1817
1818    fn three_line_tile(is_three_line: Option<bool>, subtitle: &str) -> WidgetRef {
1819        three_line_tile_of(SwitchListTile::new(false, None), is_three_line, subtitle)
1820    }
1821
1822    fn adaptive_three_line_tile(is_three_line: Option<bool>, subtitle: &str) -> WidgetRef {
1823        three_line_tile_of(
1824            SwitchListTile::adaptive(false, None),
1825            is_three_line,
1826            subtitle,
1827        )
1828    }
1829
1830    fn three_line_tile_of(
1831        tile: SwitchListTile,
1832        is_three_line: Option<bool>,
1833        subtitle: &str,
1834    ) -> WidgetRef {
1835        let mut tile = tile.title(Text::new("A")).subtitle(Text::new(subtitle));
1836        tile.is_three_line = is_three_line;
1837        tile.into_widget()
1838    }
1839
1840    fn check_is_three_line(
1841        tester: &mut WidgetTester,
1842        platform: TargetPlatform,
1843        tile: fn(Option<bool>, &str) -> WidgetRef,
1844    ) {
1845        for (frame, three_line) in IS_THREE_LINE_FRAMES {
1846            assert_eq!(
1847                is_three_line_rects::<Switch, SwitchListTile>(tester, platform, frame, tile),
1848                expected_three_line_rects(
1849                    three_line,
1850                    800.0 - 60.0 - 24.0,
1851                    Size::new(60.0, 40.0),
1852                    [130.0, 300.0 + 16.0]
1853                ),
1854                "{frame:?}"
1855            );
1856        }
1857    }
1858
1859    #[test]
1860    fn switch_list_tile_is_three_line() {
1861        test_widgets(|tester| {
1862            check_is_three_line(tester, TargetPlatform::Android, three_line_tile)
1863        });
1864    }
1865
1866    #[test]
1867    fn switch_list_tile_adaptive_is_three_line() {
1868        test_widgets(|tester| {
1869            check_is_three_line(tester, TargetPlatform::IOS, adaptive_three_line_tile)
1870        });
1871    }
1872
1873    fn check_active_thumb_color(
1874        tester: &mut WidgetTester,
1875        make: fn(bool, Option<ValueChanged<bool>>) -> SwitchListTile,
1876    ) {
1877        let root = {
1878            let app = tester.cell.borrow();
1879            crate::list_tile::tests::bare(
1880                m3(&app),
1881                Material::new().child(
1882                    make(true, ignore())
1883                        .selected(true)
1884                        .active_color(Colors::RED.shade500())
1885                        .active_thumb_color(Colors::YELLOW.shade500())
1886                        .active_track_color(Colors::GREEN.shade500())
1887                        .title(Text::new("title")),
1888                ),
1889            )
1890        };
1891        tester.pump_widget(root);
1892        assert_eq!(track(tester), Some(c(Colors::GREEN.shade500())));
1893        assert_eq!(thumb(tester), Some(c(Colors::YELLOW.shade500())));
1894        assert_eq!(tester.text_color("title"), Colors::YELLOW.shade500());
1895    }
1896
1897    #[test]
1898    fn material3_switch_list_tile_active_thumb_color() {
1899        test_widgets(|tester| check_active_thumb_color(tester, SwitchListTile::new));
1900    }
1901
1902    #[test]
1903    fn material3_switch_list_tile_adaptive_active_thumb_color() {
1904        test_widgets(|tester| check_active_thumb_color(tester, SwitchListTile::adaptive));
1905    }
1906
1907    #[test]
1908    fn switch_list_tile_does_not_crash_at_zero_area() {
1909        test_widgets(|tester| {
1910            pump_app(tester, m3, |_app| {
1911                Scaffold::new()
1912                    .body(
1913                        Center::new()
1914                            .child(SizedBox::shrink().child(SwitchListTile::new(true, ignore()))),
1915                    )
1916                    .into_widget()
1917            });
1918            assert_eq!(rect_of::<SwitchListTile>(tester, 0).size(), Size::ZERO);
1919        });
1920    }
1921
1922    fn leading_title_tile() -> SwitchListTile {
1923        SwitchListTile::new(true, ignore())
1924            .control_affinity(ListTileControlAffinity::Leading)
1925            .title(Text::new("title"))
1926    }
1927
1928    #[test]
1929    fn switch_list_tile_horizontal_title_gap_0() {
1930        test_widgets(|tester| {
1931            check_horizontal_title_gap_0(tester, [76.0, 724.0], |gap| {
1932                let mut tile = leading_title_tile();
1933                tile.horizontal_title_gap = gap;
1934                tile.into_widget()
1935            });
1936        });
1937    }
1938
1939    #[test]
1940    fn switch_list_tile_default_horizontal_title_gap_and_min_leading_width() {
1941        test_widgets(|tester| {
1942            check_default_horizontal_title_gap(tester, [92.0, 708.0], || {
1943                leading_title_tile().into_widget()
1944            });
1945        });
1946    }
1947
1948    #[test]
1949    fn switch_list_tile_horizontal_title_gap_with_visual_density() {
1950        test_widgets(|tester| {
1951            check_horizontal_title_gap_with_visual_density(tester, 78.0, || {
1952                leading_title_tile()
1953                    .visual_density(VisualDensity::new(VisualDensity::MINIMUM_DENSITY, 0.0))
1954                    .horizontal_title_gap(10.0)
1955                    .into_widget()
1956            });
1957        });
1958    }
1959
1960    fn min_vertical_padding_tile(padding: Option<f64>) -> WidgetRef {
1961        let mut tile = SwitchListTile::new(true, ignore()).title(Text::new("title"));
1962        tile.min_vertical_padding = padding;
1963        tile.into_widget()
1964    }
1965
1966    #[test]
1967    fn switch_list_tile_min_vertical_padding_80_material_3() {
1968        test_widgets(|tester| {
1969            // 80 + 80 + 24(Title) = 184
1970            check_min_vertical_padding_80(tester, m3, 184.0, min_vertical_padding_tile);
1971        });
1972    }
1973
1974    #[test]
1975    fn switch_list_tile_min_vertical_padding_80_material_2() {
1976        test_widgets(|tester| {
1977            // 80 + 80 + 16(Title) = 176
1978            check_min_vertical_padding_80(tester, m2, 176.0, min_vertical_padding_tile);
1979        });
1980    }
1981
1982    #[test]
1983    fn switch_list_tile_min_leading_width_60() {
1984        test_widgets(|tester| {
1985            check_min_leading_width_60(tester, |width| {
1986                let mut tile = leading_title_tile();
1987                tile.min_leading_width = width;
1988                tile.into_widget()
1989            });
1990        });
1991    }
1992
1993    #[test]
1994    fn switch_list_tile_min_tile_height() {
1995        test_widgets(|tester| {
1996            check_min_tile_height(tester, |min_tile_height| {
1997                let mut tile = SwitchListTile::new(true, ignore());
1998                tile.min_tile_height = min_tile_height;
1999                tile.into_widget()
2000            });
2001        });
2002    }
2003}