diff --git a/packages/flutter/lib/src/cupertino/switch.dart b/packages/flutter/lib/src/cupertino/switch.dart index 992a77b608..c354acdb84 100644 --- a/packages/flutter/lib/src/cupertino/switch.dart +++ b/packages/flutter/lib/src/cupertino/switch.dart @@ -4,11 +4,13 @@ // Examples can assume: // bool _giveVerse = false; +// bool _lights = false; +// void setState(VoidCallback fn) { } /// @docImport 'package:flutter/material.dart'; library; -import 'dart:ui' show lerpDouble; +import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; @@ -18,20 +20,61 @@ import 'package:flutter/widgets.dart'; import 'colors.dart'; import 'theme.dart'; -import 'thumb_painter.dart'; -// Examples can assume: -// bool _lights = false; -// void setState(VoidCallback fn) { } +// Hand coded defaults eyeballed from an iOS simulator running iOS version 17.5. +const double _kDisabledOpacity = 0.5; +const double _kThumbRadius = 14.0; +const double _kTrackHeight = 31.0; +const double _kTrackWidth = 51.0; +const Size _kSwitchSize = Size(59.0, 39.0); +const double _kThumbExtensionFactor = 7.0; +const List _kSwitchBoxShadows = [ + BoxShadow( + color: Color(0x26000000), + offset: Offset(0, 3), + blurRadius: 8.0, + ), + BoxShadow( + color: Color(0x0F000000), + offset: Offset(0, 3), + blurRadius: 1.0, + ), +]; + +// Label sizes and padding taken from xcode inspector. +// See https://github.com/flutter/flutter/issues/4830#issuecomment-528495360. +const double _kOnLabelWidth = 1.0; +const double _kOnLabelHeight = 10.0; +const double _kOnLabelPaddingHorizontal = 11.0; +const double _kOffLabelWidth = 1.0; +const double _kOffLabelPaddingHorizontal = 12.0; +const double _kOffLabelRadius = 5.0; +const CupertinoDynamicColor _kOffLabelColor = CupertinoDynamicColor.withBrightnessAndContrast( + debugLabel: 'offSwitchLabel', + // Source: https://github.com/flutter/flutter/pull/39993#discussion_r321946033 + color: Color.fromARGB(255, 179, 179, 179), + // Source: https://github.com/flutter/flutter/pull/39993#issuecomment-535196665 + darkColor: Color.fromARGB(255, 179, 179, 179), + // Source: https://github.com/flutter/flutter/pull/127776#discussion_r1244208264 + highContrastColor: Color.fromARGB(255, 255, 255, 255), + darkHighContrastColor: Color.fromARGB(255, 255, 255, 255), +); + +// The relative values needed to transform a color to it's equivalent focus +// outline color. +const double _kCupertinoFocusColorOpacity = 0.80; +const double _kCupertinoFocusColorBrightness = 0.69; +const double _kCupertinoFocusColorSaturation = 0.835; /// An iOS-style switch. /// /// Used to toggle the on/off state of a single setting. /// -/// The switch itself does not maintain any state. Instead, when the state of -/// the switch changes, the widget calls the [onChanged] callback. Most widgets -/// that use a switch will listen for the [onChanged] callback and rebuild the -/// switch with a new [value] to update the visual appearance of the switch. +/// The switch itself does not maintain its toggle state. Instead, when the +/// toggle state of the switch changes, the widget calls the [onChanged] +/// callback. Most widgets that use a switch will listen for the [onChanged] +/// callback and rebuild the switch with a new [value] to update the visual +/// appearance of the switch. /// /// {@tool dartpad} /// This example shows a toggleable [CupertinoSwitch]. When the thumb slides to @@ -67,6 +110,11 @@ import 'thumb_painter.dart'; class CupertinoSwitch extends StatefulWidget { /// Creates an iOS-style switch. /// + /// The following arguments are required: + /// + /// * [value] determines whether this switch is on or off. + /// * [onChanged] is called when the user toggles the switch on or off. + /// /// The [dragStartBehavior] parameter defaults to [DragStartBehavior.start]. const CupertinoSwitch({ super.key, @@ -75,20 +123,30 @@ class CupertinoSwitch extends StatefulWidget { this.activeColor, this.trackColor, this.thumbColor, + this.inactiveThumbColor, this.applyTheme, this.focusColor, this.onLabelColor, this.offLabelColor, + this.activeThumbImage, + this.onActiveThumbImageError, + this.inactiveThumbImage, + this.onInactiveThumbImageError, + this.trackOutlineColor, + this.trackOutlineWidth, + this.thumbIcon, + this.mouseCursor, this.focusNode, this.onFocusChange, this.autofocus = false, this.dragStartBehavior = DragStartBehavior.start, - }); + }) : assert(activeThumbImage != null || onActiveThumbImageError == null), + assert(inactiveThumbImage != null || onInactiveThumbImageError == null); /// Whether this switch is on or off. final bool value; - /// Called when the user toggles with switch on or off. + /// Called when the user toggles the switch on or off. /// /// The switch passes the new value to the callback but does not actually /// change state until the parent widget rebuilds the switch with the new @@ -96,7 +154,7 @@ class CupertinoSwitch extends StatefulWidget { /// /// If null, the switch will be displayed as disabled, which has a reduced opacity. /// - /// The callback provided to onChanged should update the state of the parent + /// The callback provided to [onChanged] should update the state of the parent /// [StatefulWidget] using the [State.setState] method, so that the parent /// gets rebuilt; for example: /// @@ -117,22 +175,52 @@ class CupertinoSwitch extends StatefulWidget { /// If null and [applyTheme] is false, defaults to [CupertinoColors.systemGreen] /// in accordance to native iOS behavior. Otherwise, defaults to /// [CupertinoThemeData.primaryColor]. + /// + /// See also: + /// + /// * [trackColor], the color to use for the track when the switch is off. final Color? activeColor; - /// The color to use for the track when the switch is off. /// /// Defaults to [CupertinoColors.secondarySystemFill] when null. + /// + /// See also: + /// + /// * [activeColor], the color to use for the track when the switch is on. final Color? trackColor; - /// The color to use for the thumb of the switch. + /// The color to use for the thumb when the switch is on. + /// + /// If this color is not opaque, it is blended against + /// [CupertinoThemeData.scaffoldBackgroundColor], so as not to see through the + /// thumb to the track underneath. /// /// Defaults to [CupertinoColors.white] when null. + /// + /// See also: + /// + /// * [inactiveThumbColor], the color to use for the thumb when the switch is off. final Color? thumbColor; + /// The color to use on the thumb when the switch is off. + /// + /// If this color is not opaque, it is blended against + /// [CupertinoThemeData.scaffoldBackgroundColor], so as not to see through the + /// thumb to the track underneath. + /// + /// If null, defaults to [thumbColor]. If that is also null, + /// [CupertinoColors.white] is used. + /// + /// See also: + /// + /// * [thumbColor], the color to use for the thumb when the switch is on. + final Color? inactiveThumbColor; + /// The color to use for the focus highlight for keyboard interactions. /// - /// Defaults to a slightly transparent [activeColor]. + /// Defaults to [activeColor] with an opacity of 0.80, a brightness of 0.69 + /// and a saturation of 0.835. final Color? focusColor; /// The color to use for the accessibility label when the switch is on. @@ -146,10 +234,157 @@ class CupertinoSwitch extends StatefulWidget { /// (or [Color.fromARGB(255, 255, 255, 255)] in high contrast) when null. final Color? offLabelColor; + /// {@macro flutter.material.switch.activeThumbImage} + final ImageProvider? activeThumbImage; + + /// {@macro flutter.material.switch.onActiveThumbImageError} + final ImageErrorListener? onActiveThumbImageError; + + /// {@macro flutter.material.switch.inactiveThumbImage} + final ImageProvider? inactiveThumbImage; + + /// {@macro flutter.material.switch.onInactiveThumbImageError} + final ImageErrorListener? onInactiveThumbImageError; + + /// The outline color of this [CupertinoSwitch]'s track. + /// + /// Resolved in the following states: + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. + /// + /// {@tool snippet} + /// This example resolves the [trackOutlineColor] based on the current + /// [WidgetState] of the [CupertinoSwitch], providing a different [Color] when it is + /// [WidgetState.disabled]. + /// + /// ```dart + /// CupertinoSwitch( + /// value: true, + /// onChanged: (bool value) { }, + /// trackOutlineColor: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { + /// return CupertinoColors.activeOrange.withOpacity(.48); + /// } + /// return null; // Use the default color. + /// }), + /// ) + /// ``` + /// {@end-tool} + /// + /// The [CupertinoSwitch] track has no outline by default. + final WidgetStateProperty? trackOutlineColor; + + /// The outline width of this [CupertinoSwitch]'s track. + /// + /// Resolved in the following states: + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. + /// + /// {@tool snippet} + /// This example resolves the [trackOutlineWidth] based on the current + /// [WidgetState] of the [CupertinoSwitch], providing a different outline width when it is + /// [WidgetState.disabled]. + /// + /// ```dart + /// CupertinoSwitch( + /// value: true, + /// onChanged: (bool value) { }, + /// trackOutlineWidth: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { + /// return 5.0; + /// } + /// return null; // Use the default width. + /// }), + /// ) + /// ``` + /// {@end-tool} + /// + /// Since a [CupertinoSwitch] has no track outline by default, this parameter + /// is set only if [trackOutlineColor] is provided. + /// + /// Defaults to 2.0 if a [trackOutlineColor] is provided. + final WidgetStateProperty? trackOutlineWidth; + + /// The icon to use on the thumb of this switch. + /// + /// Resolved in the following states: + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. + /// + /// {@tool snippet} + /// This example resolves the [thumbIcon] based on the current + /// [WidgetState] of the [CupertinoSwitch], providing a different [Icon] when it is + /// [WidgetState.disabled]. + /// + /// ```dart + /// CupertinoSwitch( + /// value: true, + /// onChanged: (bool value) { }, + /// thumbIcon: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { + /// return const Icon(Icons.close); + /// } + /// return null; // All other states will use the default thumbIcon. + /// }), + /// ) + /// ``` + /// {@end-tool} + /// + /// If null, then the [CupertinoSwitch] does not have any icons on the thumb. + final WidgetStateProperty? thumbIcon; + + /// The cursor for a mouse pointer when it enters or is hovering over the + /// widget. + /// + /// Resolved in the following states: + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. + /// + /// {@tool snippet} + /// This example resolves the [mouseCursor] based on the current + /// [WidgetState] of the [CupertinoSwitch], providing a different [mouseCursor] when it is + /// [WidgetState.disabled]. + /// + /// ```dart + /// CupertinoSwitch( + /// value: true, + /// onChanged: (bool value) { }, + /// mouseCursor: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { + /// return SystemMouseCursors.click; + /// } + /// return SystemMouseCursors.basic; // All other states will use the default mouseCursor. + /// }), + /// ) + /// ``` + /// {@end-tool} + /// + /// If null, then [MouseCursor.defer] is used when the switch is disabled. + /// When the switch is enabled, [SystemMouseCursors.click] is used on Web, and + /// [MouseCursor.defer] is used on other platforms. + /// + /// See also: + /// + /// * [WidgetStateMouseCursor], a [MouseCursor] that implements + /// `WidgetStateProperty` which is used in APIs that need to accept + /// either a [MouseCursor] or a [WidgetStateProperty]. + final WidgetStateProperty? mouseCursor; + /// {@macro flutter.widgets.Focus.focusNode} final FocusNode? focusNode; - /// {@macro flutter.material.inkwell.onFocusChange} + /// Handler called when the focus changes. + /// + /// Called with true if this widget's node gains focus, and false if it loses + /// focus. final ValueChanged? onFocusChange; /// {@macro flutter.widgets.Focus.autofocus} @@ -198,123 +433,94 @@ class CupertinoSwitch extends StatefulWidget { } } -class _CupertinoSwitchState extends State with TickerProviderStateMixin { - late TapGestureRecognizer _tap; - late HorizontalDragGestureRecognizer _drag; - - late AnimationController _positionController; - late final CurvedAnimation position; - - late AnimationController _reactionController; - late CurvedAnimation _reaction; - - late bool isFocused; - - bool get isInteractive => widget.onChanged != null; - - late final Map> _actionMap = >{ - ActivateIntent: CallbackAction(onInvoke: _handleTap), - }; - - // A non-null boolean value that changes to true at the end of a drag if the - // switch must be animated to the position indicated by the widget's value. - bool needsPositionAnimation = false; +class _CupertinoSwitchState extends State with TickerProviderStateMixin, ToggleableStateMixin { + final _SwitchPainter _painter = _SwitchPainter(); @override void initState() { super.initState(); - - isFocused = false; - - _tap = TapGestureRecognizer() - ..onTapDown = _handleTapDown - ..onTapUp = _handleTapUp - ..onTap = _handleTap - ..onTapCancel = _handleTapCancel; - _drag = HorizontalDragGestureRecognizer() - ..onStart = _handleDragStart - ..onUpdate = _handleDragUpdate - ..onEnd = _handleDragEnd - ..dragStartBehavior = widget.dragStartBehavior; - - _positionController = AnimationController( - duration: _kToggleDuration, - value: widget.value ? 1.0 : 0.0, - vsync: this, - ); - position = CurvedAnimation( - parent: _positionController, - curve: Curves.linear, - ); - _reactionController = AnimationController( - duration: _kReactionDuration, - vsync: this, - ); - _reaction = CurvedAnimation( - parent: _reactionController, - curve: Curves.ease, - ); + positionController.duration = const Duration(milliseconds: 200); + reactionController.duration = const Duration(milliseconds: 300); } @override void didUpdateWidget(CupertinoSwitch oldWidget) { super.didUpdateWidget(oldWidget); - _drag.dragStartBehavior = widget.dragStartBehavior; - - if (needsPositionAnimation || oldWidget.value != widget.value) { - _resumePositionAnimation(isLinear: needsPositionAnimation); + if (oldWidget.value != widget.value) { + position + ..curve = Curves.ease + ..reverseCurve = Curves.ease.flipped; + animateToValue(); } } - // `isLinear` must be true if the position animation is trying to move the - // thumb to the closest end after the most recent drag animation, so the curve - // does not change when the controller's value is not 0 or 1. - // - // It can be set to false when it's an implicit animation triggered by - // widget.value changes. - void _resumePositionAnimation({ bool isLinear = true }) { - needsPositionAnimation = false; - position - ..curve = isLinear ? Curves.linear : Curves.ease - ..reverseCurve = isLinear ? Curves.linear : Curves.ease.flipped; - if (widget.value) { - _positionController.forward(); - } else { - _positionController.reverse(); - } + @override + void dispose() { + _painter.dispose(); + super.dispose(); } - void _handleTapDown(TapDownDetails details) { - if (isInteractive) { - needsPositionAnimation = false; - } - _reactionController.forward(); + @override + ValueChanged? get onChanged => widget.onChanged != null + ? _handleChanged + : null; + + @override + bool get tristate => false; + + @override + bool? get value => widget.value; + + WidgetStateProperty get _widgetThumbColor { + return WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { + return widget.thumbColor; + } + return widget.inactiveThumbColor; + }); } - void _handleTap([Intent? _]) { - if (isInteractive) { - widget.onChanged!(!widget.value); - _emitVibration(); - } + WidgetStateProperty get _widgetTrackColor { + return WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { + return widget.activeColor; + } + return widget.trackColor; + }); } - void _handleTapUp(TapUpDetails details) { - if (isInteractive) { - needsPositionAnimation = false; - _reactionController.reverse(); + WidgetStateProperty get _defaultMouseCursor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.disabled)) { + return MouseCursor.defer; + } + return kIsWeb ? SystemMouseCursors.click : MouseCursor.defer; + }); + + Color? _resolveTrackColor(Color? trackColor, Set states) { + if (trackColor is WidgetStateColor) { + return WidgetStateProperty.resolveAs(trackColor, states); } + return trackColor; } - void _handleTapCancel() { - if (isInteractive) { - _reactionController.reverse(); + Color? _resolveThumbColor(Color? thumbColor, Set states) { + if (thumbColor is WidgetStateColor) { + return WidgetStateProperty.resolveAs(thumbColor, states); } + return thumbColor; + } + + double get _trackInnerLength { + const double trackInnerStart = _kTrackHeight / 2.0; + const double trackInnerEnd = _kTrackWidth - trackInnerStart; + const double trackInnerLength = trackInnerEnd - trackInnerStart; + return trackInnerLength; } void _handleDragStart(DragStartDetails details) { if (isInteractive) { - needsPositionAnimation = false; - _reactionController.forward(); + reactionController.forward(); _emitVibration(); } } @@ -324,22 +530,35 @@ class _CupertinoSwitchState extends State with TickerProviderSt position ..curve = Curves.linear ..reverseCurve = Curves.linear; - final double delta = details.primaryDelta! / _kTrackInnerLength; - _positionController.value += switch (Directionality.of(context)) { + final double delta = details.primaryDelta! / _trackInnerLength; + positionController.value += switch (Directionality.of(context)) { TextDirection.rtl => -delta, TextDirection.ltr => delta, }; } } + bool _needsPositionAnimation = false; + void _handleDragEnd(DragEndDetails details) { - // Deferring the animation to the next build phase. - setState(() { needsPositionAnimation = true; }); - // Call onChanged when the user's intent to change value is clear. if (position.value >= 0.5 != widget.value) { - widget.onChanged!(!widget.value); + widget.onChanged?.call(!widget.value); + // Wait to finish the animation until widget.value has changed to + // !widget.value as part of the widget.onChanged call above. + setState(() { + _needsPositionAnimation = true; + }); + } else { + animateToValue(); } - _reactionController.reverse(); + reactionController.reverse(); + } + + void _handleChanged(bool? value) { + assert(value != null); + assert(widget.onChanged != null); + widget.onChanged?.call(value!); + _emitVibration(); } void _emitVibration() { @@ -355,283 +574,387 @@ class _CupertinoSwitchState extends State with TickerProviderSt } } - void _onShowFocusHighlight(bool showHighlight) { - setState(() { isFocused = showHighlight; }); - } - @override Widget build(BuildContext context) { + if (_needsPositionAnimation) { + _needsPositionAnimation = false; + animateToValue(); + } + final CupertinoThemeData theme = CupertinoTheme.of(context); + final Color activeColor = CupertinoDynamicColor.resolve( widget.activeColor ?? ((widget.applyTheme ?? theme.applyThemeToAll) ? theme.primaryColor : null) ?? CupertinoColors.systemGreen, context, ); + final (Color onLabelColor, Color offLabelColor)? onOffLabelColors = - MediaQuery.onOffSwitchLabelsOf(context) - ? ( - CupertinoDynamicColor.resolve( - widget.onLabelColor ?? CupertinoColors.white, - context, - ), - CupertinoDynamicColor.resolve( - widget.offLabelColor ?? _kOffLabelColor, - context, - ), - ) - : null; - if (needsPositionAnimation) { - _resumePositionAnimation(); - } - return MouseRegion( - cursor: isInteractive && kIsWeb ? SystemMouseCursors.click : MouseCursor.defer, - child: Opacity( - opacity: widget.onChanged == null ? _kCupertinoSwitchDisabledOpacity : 1.0, - child: FocusableActionDetector( - onShowFocusHighlight: _onShowFocusHighlight, - actions: _actionMap, - enabled: isInteractive, - focusNode: widget.focusNode, - onFocusChange: widget.onFocusChange, - autofocus: widget.autofocus, - child: _CupertinoSwitchRenderObjectWidget( - value: widget.value, - activeColor: activeColor, - trackColor: CupertinoDynamicColor.resolve(widget.trackColor ?? CupertinoColors.secondarySystemFill, context), - thumbColor: CupertinoDynamicColor.resolve(widget.thumbColor ?? CupertinoColors.white, context), - // Opacity, lightness, and saturation values were approximated with - // color pickers on the switches in the macOS settings. - focusColor: CupertinoDynamicColor.resolve( - widget.focusColor ?? - HSLColor - .fromColor(activeColor.withOpacity(0.80)) - .withLightness(0.69).withSaturation(0.835) + MediaQuery.onOffSwitchLabelsOf(context) + ? (CupertinoDynamicColor.resolve( + widget.onLabelColor ?? CupertinoColors.white, + context, + ), + CupertinoDynamicColor.resolve( + widget.offLabelColor ?? _kOffLabelColor, + context, + ), + ) + : null; + + // Colors need to be resolved in selected and non selected states separately + // so that they can be lerped between. + final Set activeStates = states..add(WidgetState.selected); + final Set inactiveStates = states..remove(WidgetState.selected); + + final Color effectiveActiveThumbColor = _resolveThumbColor(widget.thumbColor, activeStates) + ?? _widgetThumbColor.resolve(activeStates) + ?? CupertinoColors.white; + + final Color effectiveInactiveThumbColor = _resolveThumbColor(widget.inactiveThumbColor, inactiveStates) + ?? _widgetThumbColor.resolve(inactiveStates) + ?? effectiveActiveThumbColor; + + final Color effectiveActiveTrackColor = _widgetTrackColor.resolve(activeStates) ?? activeColor; + + final Color? effectiveActiveTrackOutlineColor = widget.trackOutlineColor?.resolve(activeStates); + + final double? effectiveActiveTrackOutlineWidth = widget.trackOutlineWidth?.resolve(activeStates); + + final Color effectiveInactiveTrackColor = _resolveTrackColor(widget.trackColor, inactiveStates) + ?? CupertinoDynamicColor.resolve(CupertinoColors.secondarySystemFill, context); + + final Color? effectiveInactiveTrackOutlineColor = widget.trackOutlineColor?.resolve(inactiveStates); + + final double? effectiveInactiveTrackOutlineWidth = widget.trackOutlineWidth?.resolve(inactiveStates); + + final Icon? effectiveActiveIcon = widget.thumbIcon?.resolve(activeStates); + + final Icon? effectiveInactiveIcon = widget.thumbIcon?.resolve(inactiveStates); + + final Color effectiveActiveIconColor = effectiveActiveIcon?.color ?? CupertinoColors.black; + + final Color effectiveInactiveIconColor = effectiveInactiveIcon?.color ?? CupertinoColors.black; + + final Set activePressedStates = activeStates..add(WidgetState.pressed); + final Color effectiveActivePressedThumbColor = _resolveThumbColor(widget.thumbColor, activePressedStates) + ?? _widgetThumbColor.resolve(activePressedStates) + ?? CupertinoColors.white; + + final Set inactivePressedStates = inactiveStates..add(WidgetState.pressed); + final Color effectiveInactivePressedThumbColor = _resolveThumbColor(widget.thumbColor, inactivePressedStates) + ?? _widgetThumbColor.resolve(inactivePressedStates) + ?? CupertinoColors.white; + + final WidgetStateProperty effectiveMouseCursor = widget.mouseCursor ?? _defaultMouseCursor; + + return Semantics( + toggled: widget.value, + child: GestureDetector( + excludeFromSemantics: true, + onHorizontalDragStart: _handleDragStart, + onHorizontalDragUpdate: _handleDragUpdate, + onHorizontalDragEnd: _handleDragEnd, + dragStartBehavior: widget.dragStartBehavior, + child: Opacity( + opacity: onChanged == null ? _kDisabledOpacity : 1, + child: buildToggleable( + mouseCursor: effectiveMouseCursor, + focusNode: widget.focusNode, + onFocusChange: widget.onFocusChange, + autofocus: widget.autofocus, + size: _kSwitchSize, + painter: _painter + ..position = position + ..reaction = reaction + ..reactionFocusFade = reactionFocusFade + ..reactionHoverFade = reactionHoverFade + ..focusColor = CupertinoDynamicColor.resolve( + widget.focusColor ?? + HSLColor + .fromColor(activeColor + .withOpacity(_kCupertinoFocusColorOpacity)) + .withLightness(_kCupertinoFocusColorBrightness) + .withSaturation(_kCupertinoFocusColorSaturation) .toColor(), - context), - onChanged: widget.onChanged, - textDirection: Directionality.of(context), - isFocused: isFocused, - state: this, - onOffLabelColors: onOffLabelColors, + context) + ..downPosition = downPosition + ..isFocused = states.contains(WidgetState.focused) + ..isHovered = states.contains(WidgetState.hovered) + ..activeColor = effectiveActiveThumbColor + ..inactiveColor = effectiveInactiveThumbColor + ..activePressedColor = effectiveActivePressedThumbColor + ..onOffLabelColors = onOffLabelColors + ..inactivePressedColor = effectiveInactivePressedThumbColor + ..activeThumbImage = widget.activeThumbImage + ..onActiveThumbImageError = widget.onActiveThumbImageError + ..inactiveThumbImage = widget.inactiveThumbImage + ..onInactiveThumbImageError = widget.onInactiveThumbImageError + ..activeTrackColor = effectiveActiveTrackColor + ..activeTrackOutlineColor = effectiveActiveTrackOutlineColor + ..activeTrackOutlineWidth = effectiveActiveTrackOutlineWidth + ..inactiveTrackColor = effectiveInactiveTrackColor + ..inactiveTrackOutlineColor = effectiveInactiveTrackOutlineColor + ..inactiveTrackOutlineWidth = effectiveInactiveTrackOutlineWidth + ..configuration = createLocalImageConfiguration(context) + ..isInteractive = isInteractive + ..trackInnerLength = _trackInnerLength + ..textDirection = Directionality.of(context) + ..activeIconColor = effectiveActiveIconColor + ..inactiveIconColor = effectiveInactiveIconColor + ..activeIcon = effectiveActiveIcon + ..inactiveIcon = effectiveInactiveIcon + ..iconTheme = IconTheme.of(context) + ..surfaceColor = theme.scaffoldBackgroundColor + ..positionController = positionController ), ), ), ); } - - @override - void dispose() { - _tap.dispose(); - _drag.dispose(); - - _positionController.dispose(); - _reactionController.dispose(); - position.dispose(); - _reaction.dispose(); - super.dispose(); - } } -class _CupertinoSwitchRenderObjectWidget extends LeafRenderObjectWidget { - const _CupertinoSwitchRenderObjectWidget({ - required this.value, - required this.activeColor, - required this.trackColor, - required this.thumbColor, - required this.focusColor, - required this.onChanged, - required this.textDirection, - required this.isFocused, - required this.state, - required this.onOffLabelColors, - }); - - final bool value; - final Color activeColor; - final Color trackColor; - final Color thumbColor; - final Color focusColor; - final ValueChanged? onChanged; - final _CupertinoSwitchState state; - final TextDirection textDirection; - final bool isFocused; - final (Color onLabelColor, Color offLabelColor)? onOffLabelColors; - - @override - _RenderCupertinoSwitch createRenderObject(BuildContext context) { - return _RenderCupertinoSwitch( - value: value, - activeColor: activeColor, - trackColor: trackColor, - thumbColor: thumbColor, - focusColor: focusColor, - onChanged: onChanged, - textDirection: textDirection, - isFocused: isFocused, - state: state, - onOffLabelColors: onOffLabelColors, +class _SwitchPainter extends ToggleablePainter { + AnimationController get positionController => _positionController!; + AnimationController? _positionController; + set positionController(AnimationController? value) { + assert(value != null); + if (value == _positionController) { + return; + } + _positionController = value; + _colorAnimation?.dispose(); + _colorAnimation = CurvedAnimation( + parent: positionController, + curve: Curves.easeOut, + reverseCurve: Curves.easeIn ); + notifyListeners(); } - @override - void updateRenderObject(BuildContext context, _RenderCupertinoSwitch renderObject) { - assert(renderObject._state == state); - renderObject - ..value = value - ..activeColor = activeColor - ..trackColor = trackColor - ..thumbColor = thumbColor - ..focusColor = focusColor - ..onChanged = onChanged - ..textDirection = textDirection - ..isFocused = isFocused; - } -} + CurvedAnimation? _colorAnimation; -const double _kTrackWidth = 51.0; -const double _kTrackHeight = 31.0; -const double _kTrackRadius = _kTrackHeight / 2.0; -const double _kTrackInnerStart = _kTrackHeight / 2.0; -const double _kTrackInnerEnd = _kTrackWidth - _kTrackInnerStart; -const double _kTrackInnerLength = _kTrackInnerEnd - _kTrackInnerStart; -const double _kSwitchWidth = 59.0; -const double _kSwitchHeight = 39.0; -// Label sizes and padding taken from xcode inspector. -// See https://github.com/flutter/flutter/issues/4830#issuecomment-528495360 -const double _kOnLabelWidth = 1.0; -const double _kOnLabelHeight = 10.0; -const double _kOnLabelPaddingHorizontal = 11.0; -const double _kOffLabelWidth = 1.0; -const double _kOffLabelPaddingHorizontal = 12.0; -const double _kOffLabelRadius = 5.0; -const CupertinoDynamicColor _kOffLabelColor = CupertinoDynamicColor.withBrightnessAndContrast( - debugLabel: 'offSwitchLabel', - // Source: https://github.com/flutter/flutter/pull/39993#discussion_r321946033 - color: Color.fromARGB(255, 179, 179, 179), - // Source: https://github.com/flutter/flutter/pull/39993#issuecomment-535196665 - darkColor: Color.fromARGB(255, 179, 179, 179), - // Source: https://github.com/flutter/flutter/pull/127776#discussion_r1244208264 - highContrastColor: Color.fromARGB(255, 255, 255, 255), - darkHighContrastColor: Color.fromARGB(255, 255, 255, 255), -); -// Opacity of a disabled switch, as eye-balled from iOS Simulator on Mac. -const double _kCupertinoSwitchDisabledOpacity = 0.5; - -const Duration _kReactionDuration = Duration(milliseconds: 300); -const Duration _kToggleDuration = Duration(milliseconds: 200); - -class _RenderCupertinoSwitch extends RenderConstrainedBox { - _RenderCupertinoSwitch({ - required bool value, - required Color activeColor, - required Color trackColor, - required Color thumbColor, - required Color focusColor, - ValueChanged? onChanged, - required TextDirection textDirection, - required bool isFocused, - required _CupertinoSwitchState state, - required (Color onLabelColor, Color offLabelColor)? onOffLabelColors, - }) : _value = value, - _activeColor = activeColor, - _trackColor = trackColor, - _focusColor = focusColor, - _thumbPainter = CupertinoThumbPainter.switchThumb(color: thumbColor), - _onChanged = onChanged, - _textDirection = textDirection, - _isFocused = isFocused, - _state = state, - _onOffLabelColors = onOffLabelColors, - super(additionalConstraints: const BoxConstraints.tightFor(width: _kSwitchWidth, height: _kSwitchHeight)) { - state.position.addListener(markNeedsPaint); - state._reaction.addListener(markNeedsPaint); - } - - final _CupertinoSwitchState _state; - - bool get value => _value; - bool _value; - set value(bool value) { - if (value == _value) { + Icon? get activeIcon => _activeIcon; + Icon? _activeIcon; + set activeIcon(Icon? value) { + if (value == _activeIcon) { return; } - _value = value; - markNeedsSemanticsUpdate(); + _activeIcon = value; + notifyListeners(); } - Color get activeColor => _activeColor; - Color _activeColor; - set activeColor(Color value) { - if (value == _activeColor) { + Icon? get inactiveIcon => _inactiveIcon; + Icon? _inactiveIcon; + set inactiveIcon(Icon? value) { + if (value == _inactiveIcon) { return; } - _activeColor = value; - markNeedsPaint(); + _inactiveIcon = value; + notifyListeners(); } - Color get trackColor => _trackColor; - Color _trackColor; - set trackColor(Color value) { - if (value == _trackColor) { + IconThemeData? get iconTheme => _iconTheme; + IconThemeData? _iconTheme; + set iconTheme(IconThemeData? value) { + if (value == _iconTheme) { return; } - _trackColor = value; - markNeedsPaint(); + _iconTheme = value; + notifyListeners(); } - Color get thumbColor => _thumbPainter.color; - CupertinoThumbPainter _thumbPainter; - set thumbColor(Color value) { - if (value == thumbColor) { + Color get activeIconColor => _activeIconColor!; + Color? _activeIconColor; + set activeIconColor(Color value) { + if (value == _activeIconColor) { return; } - _thumbPainter = CupertinoThumbPainter.switchThumb(color: value); - markNeedsPaint(); + _activeIconColor = value; + notifyListeners(); } - Color get focusColor => _focusColor; - Color _focusColor; - set focusColor(Color value) { - if (value == _focusColor) { + Color get inactiveIconColor => _inactiveIconColor!; + Color? _inactiveIconColor; + set inactiveIconColor(Color value) { + if (value == _inactiveIconColor) { return; } - _focusColor = value; - markNeedsPaint(); + _inactiveIconColor = value; + notifyListeners(); } - ValueChanged? get onChanged => _onChanged; - ValueChanged? _onChanged; - set onChanged(ValueChanged? value) { - if (value == _onChanged) { + Color get activePressedColor => _activePressedColor!; + Color? _activePressedColor; + set activePressedColor(Color? value) { + assert(value != null); + if (value == _activePressedColor) { return; } - final bool wasInteractive = isInteractive; - _onChanged = value; - if (wasInteractive != isInteractive) { - markNeedsPaint(); - markNeedsSemanticsUpdate(); - } + _activePressedColor = value; + notifyListeners(); } - TextDirection get textDirection => _textDirection; - TextDirection _textDirection; + Color get inactivePressedColor => _inactivePressedColor!; + Color? _inactivePressedColor; + set inactivePressedColor(Color? value) { + assert(value != null); + if (value == _inactivePressedColor) { + return; + } + _inactivePressedColor = value; + notifyListeners(); + } + + ImageProvider? get activeThumbImage => _activeThumbImage; + ImageProvider? _activeThumbImage; + set activeThumbImage(ImageProvider? value) { + if (value == _activeThumbImage) { + return; + } + _activeThumbImage = value; + notifyListeners(); + } + + ImageErrorListener? get onActiveThumbImageError => _onActiveThumbImageError; + ImageErrorListener? _onActiveThumbImageError; + set onActiveThumbImageError(ImageErrorListener? value) { + if (value == _onActiveThumbImageError) { + return; + } + _onActiveThumbImageError = value; + notifyListeners(); + } + + ImageProvider? get inactiveThumbImage => _inactiveThumbImage; + ImageProvider? _inactiveThumbImage; + set inactiveThumbImage(ImageProvider? value) { + if (value == _inactiveThumbImage) { + return; + } + _inactiveThumbImage = value; + notifyListeners(); + } + + ImageErrorListener? get onInactiveThumbImageError => _onInactiveThumbImageError; + ImageErrorListener? _onInactiveThumbImageError; + set onInactiveThumbImageError(ImageErrorListener? value) { + if (value == _onInactiveThumbImageError) { + return; + } + _onInactiveThumbImageError = value; + notifyListeners(); + } + + Color get activeTrackColor => _activeTrackColor!; + Color? _activeTrackColor; + set activeTrackColor(Color value) { + if (value == _activeTrackColor) { + return; + } + _activeTrackColor = value; + notifyListeners(); + } + + Color? get activeTrackOutlineColor => _activeTrackOutlineColor; + Color? _activeTrackOutlineColor; + set activeTrackOutlineColor(Color? value) { + if (value == _activeTrackOutlineColor) { + return; + } + _activeTrackOutlineColor = value; + notifyListeners(); + } + + Color? get inactiveTrackOutlineColor => _inactiveTrackOutlineColor; + Color? _inactiveTrackOutlineColor; + set inactiveTrackOutlineColor(Color? value) { + if (value == _inactiveTrackOutlineColor) { + return; + } + _inactiveTrackOutlineColor = value; + notifyListeners(); + } + + double? get activeTrackOutlineWidth => _activeTrackOutlineWidth; + double? _activeTrackOutlineWidth; + set activeTrackOutlineWidth(double? value) { + if (value == _activeTrackOutlineWidth) { + return; + } + _activeTrackOutlineWidth = value; + notifyListeners(); + } + + double? get inactiveTrackOutlineWidth => _inactiveTrackOutlineWidth; + double? _inactiveTrackOutlineWidth; + set inactiveTrackOutlineWidth(double? value) { + if (value == _inactiveTrackOutlineWidth) { + return; + } + _inactiveTrackOutlineWidth = value; + notifyListeners(); + } + + Color get inactiveTrackColor => _inactiveTrackColor!; + Color? _inactiveTrackColor; + set inactiveTrackColor(Color value) { + if (value == _inactiveTrackColor) { + return; + } + _inactiveTrackColor = value; + notifyListeners(); + } + + ImageConfiguration get configuration => _configuration!; + ImageConfiguration? _configuration; + set configuration(ImageConfiguration value) { + if (value == _configuration) { + return; + } + _configuration = value; + notifyListeners(); + } + + TextDirection get textDirection => _textDirection!; + TextDirection? _textDirection; set textDirection(TextDirection value) { if (_textDirection == value) { return; } _textDirection = value; - markNeedsPaint(); + notifyListeners(); } - bool get isFocused => _isFocused; - bool _isFocused; - set isFocused(bool value) { - if (value == _isFocused) { + Color get surfaceColor => _surfaceColor!; + Color? _surfaceColor; + set surfaceColor(Color value) { + if (value == _surfaceColor) { return; } - _isFocused = value; - markNeedsPaint(); + _surfaceColor = value; + notifyListeners(); + } + + bool get isInteractive => _isInteractive!; + bool? _isInteractive; + set isInteractive(bool value) { + if (value == _isInteractive) { + return; + } + _isInteractive = value; + notifyListeners(); + } + + double get trackInnerLength => _trackInnerLength!; + double? _trackInnerLength; + set trackInnerLength(double value) { + if (value == _trackInnerLength) { + return; + } + _trackInnerLength = value; + notifyListeners(); } (Color onLabelColor, Color offLabelColor)? get onOffLabelColors => _onOffLabelColors; @@ -641,95 +964,128 @@ class _RenderCupertinoSwitch extends RenderConstrainedBox { return; } _onOffLabelColors = value; - markNeedsPaint(); + notifyListeners(); } - bool get isInteractive => onChanged != null; + final TextPainter _textPainter = TextPainter(); + Color? _cachedThumbColor; + ImageProvider? _cachedThumbImage; + ImageErrorListener? _cachedThumbErrorListener; + BoxPainter? _cachedThumbPainter; - @override - bool hitTestSelf(Offset position) => true; + ShapeDecoration _createDefaultThumbDecoration(Color color, ImageProvider? image, ImageErrorListener? errorListener) { + return ShapeDecoration( + color: color, + image: image == null + ? null + : DecorationImage(image: image, onError: errorListener), + shape: const StadiumBorder(), + ); + } - @override - void handleEvent(PointerEvent event, BoxHitTestEntry entry) { - assert(debugHandleEvent(event, entry)); - if (event is PointerDownEvent && isInteractive) { - _state._drag.addPointer(event); - _state._tap.addPointer(event); + bool _isPainting = false; + + void _handleDecorationChanged() { + // If the image decoration is available synchronously, we'll get called here + // during paint. There's no reason to mark ourselves as needing paint if we + // are already in the middle of painting. (In fact, doing so would trigger + // an assert). + if (!_isPainting) { + notifyListeners(); } } - @override - void describeSemanticsConfiguration(SemanticsConfiguration config) { - super.describeSemanticsConfiguration(config); - - if (isInteractive) { - config.onTap = _state._handleTap; - } - - config.isEnabled = isInteractive; - config.isToggled = _value; - } + bool _stopPressAnimation = false; + late double? _pressedThumbExtension; @override - void paint(PaintingContext context, Offset offset) { - final Canvas canvas = context.canvas; - - final double currentValue = _state.position.value; - final double currentReactionValue = _state._reaction.value; + void paint(Canvas canvas, Size size) { + final double currentValue = position.value; final double visualPosition = switch (textDirection) { TextDirection.rtl => 1.0 - currentValue, TextDirection.ltr => currentValue, }; - - final Paint paint = Paint() - ..color = Color.lerp(trackColor, activeColor, currentValue)!; - - final Rect trackRect = Rect.fromLTWH( - offset.dx + (size.width - _kTrackWidth) / 2.0, - offset.dy + (size.height - _kTrackHeight) / 2.0, - _kTrackWidth, - _kTrackHeight, - ); - final RRect trackRRect = RRect.fromRectAndRadius(trackRect, const Radius.circular(_kTrackRadius)); - canvas.drawRRect(trackRRect, paint); - - if (_isFocused) { - // Paints a border around the switch in the focus color. - final RRect borderTrackRRect = trackRRect.inflate(1.75); - - final Paint borderPaint = Paint() - ..color = focusColor - ..style = PaintingStyle.stroke - ..strokeWidth = 3.5; - - canvas.drawRRect(borderTrackRRect, borderPaint); + if (reaction.status == AnimationStatus.reverse && !_stopPressAnimation) { + _stopPressAnimation = true; + } else { + _stopPressAnimation = false; } + _pressedThumbExtension = reaction.value * _kThumbExtensionFactor; + final Size thumbSize = Size( + _kThumbRadius * 2 + _pressedThumbExtension!, + _kThumbRadius * 2, + ); + + final double colorValue = _colorAnimation!.value; + final Color trackColor = Color.lerp(inactiveTrackColor, activeTrackColor, position.value)!; + final Color? trackOutlineColor = inactiveTrackOutlineColor == null || activeTrackOutlineColor == null + ? null + : Color.lerp(inactiveTrackOutlineColor, activeTrackOutlineColor, colorValue); + final double? trackOutlineWidth = lerpDouble(inactiveTrackOutlineWidth, activeTrackOutlineWidth, colorValue); + + final Color lerpedThumbColor; + if (!reaction.isDismissed) { + lerpedThumbColor = Color.lerp(inactivePressedColor, activePressedColor, colorValue)!; + } else if (positionController.status == AnimationStatus.forward) { + lerpedThumbColor = Color.lerp(inactivePressedColor, activeColor, colorValue)!; + } else if (positionController.status == AnimationStatus.reverse) { + lerpedThumbColor = Color.lerp(inactiveColor, activePressedColor, colorValue)!; + } else { + lerpedThumbColor = Color.lerp(inactiveColor, activeColor, colorValue)!; + } + + // Blend the thumb color against a `surfaceColor` background in case the + // thumbColor is not opaque. This way we do not see through the thumb to the + // track underneath. + final Color thumbColor = Color.alphaBlend(lerpedThumbColor, surfaceColor); + + final Icon? thumbIcon = currentValue < 0.5 ? inactiveIcon : activeIcon; + + final ImageProvider? thumbImage = currentValue < 0.5 ? inactiveThumbImage : activeThumbImage; + + final ImageErrorListener? thumbErrorListener = currentValue < 0.5 + ? onInactiveThumbImageError + : onActiveThumbImageError; + + final Paint paint = Paint()..color = trackColor; + + final Offset trackPaintOffset = _computeTrackPaintOffset(size); + final Offset thumbPaintOffset = _computeThumbPaintOffset(trackPaintOffset, thumbSize, visualPosition); + + final Rect trackRect = Rect.fromLTWH( + trackPaintOffset.dx, + trackPaintOffset.dy, + _kTrackWidth, + _kTrackHeight, + ); + + _paintTrackWith(canvas, paint, trackPaintOffset, trackOutlineColor, trackOutlineWidth, trackRect); + + final double currentReactionValue = reaction.value; if (_onOffLabelColors != null) { final (Color onLabelColor, Color offLabelColor) = onOffLabelColors!; final double leftLabelOpacity = visualPosition * (1.0 - currentReactionValue); final double rightLabelOpacity = (1.0 - visualPosition) * (1.0 - currentReactionValue); - final (double onLabelOpacity, double offLabelOpacity) = - switch (textDirection) { + final (double onLabelOpacity, double offLabelOpacity) = switch (textDirection) { TextDirection.ltr => (leftLabelOpacity, rightLabelOpacity), TextDirection.rtl => (rightLabelOpacity, leftLabelOpacity), }; - final (Offset onLabelOffset, Offset offLabelOffset) = - switch (textDirection) { + final (Offset onLabelOffset, Offset offLabelOffset) = switch (textDirection) { TextDirection.ltr => ( - trackRect.centerLeft.translate(_kOnLabelPaddingHorizontal, 0), - trackRect.centerRight.translate(-_kOffLabelPaddingHorizontal, 0), - ), + trackRect.centerLeft.translate(_kOnLabelPaddingHorizontal, 0), + trackRect.centerRight.translate(-_kOffLabelPaddingHorizontal, 0), + ), TextDirection.rtl => ( - trackRect.centerRight.translate(-_kOnLabelPaddingHorizontal, 0), - trackRect.centerLeft.translate(_kOffLabelPaddingHorizontal, 0), - ), + trackRect.centerRight.translate(-_kOnLabelPaddingHorizontal, 0), + trackRect.centerLeft.translate(_kOffLabelPaddingHorizontal, 0), + ), }; - // Draws '|' label + // Draws '|' label. final Rect onLabelRect = Rect.fromCenter( center: onLabelOffset, width: _kOnLabelWidth, @@ -740,7 +1096,7 @@ class _RenderCupertinoSwitch extends RenderConstrainedBox { ..style = PaintingStyle.fill; canvas.drawRect(onLabelRect, onLabelPaint); - // Draws 'O' label + // Draws 'O' label. final Paint offLabelPaint = Paint() ..color = offLabelColor.withOpacity(offLabelOpacity) ..style = PaintingStyle.stroke @@ -751,43 +1107,178 @@ class _RenderCupertinoSwitch extends RenderConstrainedBox { offLabelPaint, ); } - - final double currentThumbExtension = CupertinoThumbPainter.extension * currentReactionValue; - final double thumbLeft = lerpDouble( - trackRect.left + _kTrackInnerStart - CupertinoThumbPainter.radius, - trackRect.left + _kTrackInnerEnd - CupertinoThumbPainter.radius - currentThumbExtension, - visualPosition, - )!; - final double thumbRight = lerpDouble( - trackRect.left + _kTrackInnerStart + CupertinoThumbPainter.radius + currentThumbExtension, - trackRect.left + _kTrackInnerEnd + CupertinoThumbPainter.radius, - visualPosition, - )!; - final double thumbCenterY = offset.dy + size.height / 2.0; - final Rect thumbBounds = Rect.fromLTRB( - thumbLeft, - thumbCenterY - CupertinoThumbPainter.radius, - thumbRight, - thumbCenterY + CupertinoThumbPainter.radius, + _paintThumbWith( + thumbPaintOffset, + canvas, + colorValue, + thumbColor, + thumbImage, + thumbErrorListener, + thumbIcon, + thumbSize, ); - - _clipRRectLayer.layer = context.pushClipRRect(needsCompositing, Offset.zero, thumbBounds, trackRRect, (PaintingContext innerContext, Offset offset) { - _thumbPainter.paint(innerContext.canvas, thumbBounds); - }, oldLayer: _clipRRectLayer.layer); } - final LayerHandle _clipRRectLayer = LayerHandle(); + /// Computes canvas offset for track's upper left corner. + static Offset _computeTrackPaintOffset(Size canvasSize) { + final double horizontalOffset = (canvasSize.width - _kTrackWidth) / 2.0; + final double verticalOffset = (canvasSize.height - _kTrackHeight) / 2.0; + + return Offset(horizontalOffset, verticalOffset); + } + + /// Computes canvas offset for thumb's upper left corner as if it were a + /// square. + Offset _computeThumbPaintOffset(Offset trackPaintOffset, Size thumbSize, double visualPosition) { + // How much the thumb radius extends beyond the track. + const double trackRadius = _kTrackHeight / 2; + final double additionalThumbRadius = thumbSize.height / 2 - trackRadius; + + final double horizontalProgress = visualPosition * (trackInnerLength - _pressedThumbExtension!); + final double thumbHorizontalOffset = trackPaintOffset.dx + trackRadius + (_pressedThumbExtension! / 2) - thumbSize.width / 2 + horizontalProgress; + final double thumbVerticalOffset = trackPaintOffset.dy - additionalThumbRadius; + return Offset(thumbHorizontalOffset, thumbVerticalOffset); + } + + void _paintTrackWith(Canvas canvas, Paint paint, Offset trackPaintOffset, Color? trackOutlineColor, double? trackOutlineWidth, Rect trackRect) { + const double trackRadius = _kTrackHeight / 2; + final RRect trackRRect = RRect.fromRectAndRadius( + trackRect, + const Radius.circular(trackRadius), + ); + + canvas.drawRRect(trackRRect, paint); + + // Paint the track outline. + if (trackOutlineColor != null) { + final Rect outlineTrackRect = Rect.fromLTWH( + trackPaintOffset.dx + 1, + trackPaintOffset.dy + 1, + _kTrackWidth - 2, + _kTrackHeight - 2, + ); + final RRect outlineTrackRRect = RRect.fromRectAndRadius( + outlineTrackRect, + const Radius.circular(trackRadius), + ); + + final Paint outlinePaint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = trackOutlineWidth ?? 2.0 + ..color = trackOutlineColor; + + canvas.drawRRect(outlineTrackRRect, outlinePaint); + } + + if (isFocused) { + final RRect focusedOutline = trackRRect.inflate(1.75); + final Paint focusedPaint = Paint() + ..style = PaintingStyle.stroke + ..color = focusColor + ..strokeWidth = 3.5; + canvas.drawRRect(focusedOutline, focusedPaint); + } + canvas.clipRRect(trackRRect); + } + + void _paintThumbWith( + Offset thumbPaintOffset, + Canvas canvas, + double currentValue, + Color thumbColor, + ImageProvider? thumbImage, + ImageErrorListener? thumbErrorListener, + Icon? thumbIcon, + Size thumbSize, + ) { + try { + _isPainting = true; + if (_cachedThumbPainter == null || thumbColor != _cachedThumbColor || thumbImage != _cachedThumbImage || thumbErrorListener != _cachedThumbErrorListener) { + _cachedThumbColor = thumbColor; + _cachedThumbImage = thumbImage; + _cachedThumbErrorListener = thumbErrorListener; + _cachedThumbPainter?.dispose(); + _cachedThumbPainter = _createDefaultThumbDecoration(thumbColor, thumbImage, thumbErrorListener) + .createBoxPainter(_handleDecorationChanged); + } + final BoxPainter thumbPainter = _cachedThumbPainter!; + + _paintCupertinoThumbShadowAndBorder(canvas, thumbPaintOffset, thumbSize); + + thumbPainter.paint( + canvas, + thumbPaintOffset, + configuration.copyWith(size: thumbSize), + ); + + if (thumbIcon != null && thumbIcon.icon != null) { + final Color iconColor = Color.lerp(inactiveIconColor, activeIconColor, currentValue)!; + final double iconSize = thumbIcon.size ?? 16.0; + final IconData iconData = thumbIcon.icon!; + final double? iconWeight = thumbIcon.weight ?? iconTheme?.weight; + final double? iconFill = thumbIcon.fill ?? iconTheme?.fill; + final double? iconGrade = thumbIcon.grade ?? iconTheme?.grade; + final double? iconOpticalSize = thumbIcon.opticalSize ?? iconTheme?.opticalSize; + final List? iconShadows = thumbIcon.shadows ?? iconTheme?.shadows; + + final TextSpan textSpan = TextSpan( + text: String.fromCharCode(iconData.codePoint), + style: TextStyle( + fontVariations: [ + if (iconFill != null) FontVariation('FILL', iconFill), + if (iconWeight != null) FontVariation('wght', iconWeight), + if (iconGrade != null) FontVariation('GRAD', iconGrade), + if (iconOpticalSize != null) FontVariation('opsz', iconOpticalSize), + ], + color: iconColor, + fontSize: iconSize, + inherit: false, + fontFamily: iconData.fontFamily, + package: iconData.fontPackage, + shadows: iconShadows, + ), + ); + _textPainter + ..textDirection = textDirection + ..text = textSpan; + _textPainter.layout(); + final double additionalHorizontalOffset = (thumbSize.width - iconSize) / 2; + final double additionalVerticalOffset = (thumbSize.height - iconSize) / 2; + final Offset offset = thumbPaintOffset + Offset(additionalHorizontalOffset, additionalVerticalOffset); + + _textPainter.paint(canvas, offset); + } + } finally { + _isPainting = false; + } + } + + void _paintCupertinoThumbShadowAndBorder(Canvas canvas, Offset thumbPaintOffset, Size thumbSize) { + final RRect thumbBounds = RRect.fromLTRBR( + thumbPaintOffset.dx, + thumbPaintOffset.dy, + thumbPaintOffset.dx + thumbSize.width, + thumbPaintOffset.dy + thumbSize.height, + Radius.circular(thumbSize.height / 2.0), + ); + for (final BoxShadow shadow in _kSwitchBoxShadows) { + canvas.drawRRect(thumbBounds.shift(shadow.offset), shadow.toPaint()); + } + canvas.drawRRect( + thumbBounds.inflate(0.5), + Paint()..color = const Color(0x0A000000), + ); + } @override void dispose() { - _clipRRectLayer.layer = null; + _textPainter.dispose(); + _cachedThumbPainter?.dispose(); + _cachedThumbPainter = null; + _cachedThumbColor = null; + _cachedThumbImage = null; + _cachedThumbErrorListener = null; + _colorAnimation?.dispose(); super.dispose(); } - - @override - void debugFillProperties(DiagnosticPropertiesBuilder description) { - super.debugFillProperties(description); - description.add(FlagProperty('value', value: value, ifTrue: 'checked', ifFalse: 'unchecked', showName: true)); - description.add(FlagProperty('isInteractive', value: isInteractive, ifTrue: 'enabled', ifFalse: 'disabled', showName: true, defaultValue: true)); - } } diff --git a/packages/flutter/lib/src/cupertino/thumb_painter.dart b/packages/flutter/lib/src/cupertino/thumb_painter.dart index 86bfdedbb4..091f2a8b73 100644 --- a/packages/flutter/lib/src/cupertino/thumb_painter.dart +++ b/packages/flutter/lib/src/cupertino/thumb_painter.dart @@ -45,7 +45,7 @@ const List _kSliderBoxShadows = [ /// Paints an iOS-style slider thumb or switch thumb. /// -/// Used by [CupertinoSwitch] and [CupertinoSlider]. +/// Used by [CupertinoSlider]. class CupertinoThumbPainter { /// Creates an object that paints an iOS-style slider thumb. const CupertinoThumbPainter({ diff --git a/packages/flutter/test/cupertino/switch_test.dart b/packages/flutter/test/cupertino/switch_test.dart index 4ddfeffc12..0ff292a0aa 100644 --- a/packages/flutter/test/cupertino/switch_test.dart +++ b/packages/flutter/test/cupertino/switch_test.dart @@ -7,6 +7,9 @@ @Tags(['reduced-test-set']) library; +import 'dart:async'; +import 'dart:ui' as ui; + import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; @@ -15,6 +18,8 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; +import '../widgets/semantics_tester.dart'; + void main() { testWidgets('Switch can toggle on tap', (WidgetTester tester) async { final Key switchKey = UniqueKey(); @@ -620,6 +625,53 @@ void main() { ); }); + testWidgets('Switch can set active/inactive thumb colors', (WidgetTester tester) async { + bool value = false; + const Color activeThumbColor = Color(0xff00000A); + const Color inactiveThumbColor = Color(0xff00000B); + + await tester.pumpWidget( + CupertinoApp( + home: Directionality( + textDirection: TextDirection.rtl, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return CupertinoPageScaffold( + child: Center( + child: CupertinoSwitch( + dragStartBehavior: DragStartBehavior.down, + value: value, + onChanged: (bool newValue) { + setState(() { + value = newValue; + }); + }, + thumbColor: activeThumbColor, + inactiveThumbColor: inactiveThumbColor, + ), + ), + ); + }, + ), + ), + ), + ); + expect( + find.byType(CupertinoSwitch), + paints + ..rrect()..rrect()..rrect()..rrect() + ..rrect(color: inactiveThumbColor), + ); + await tester.drag(find.byType(CupertinoSwitch), const Offset(-30.0, 0.0)); + await tester.pump(); + expect( + find.byType(CupertinoSwitch), + paints + ..rrect()..rrect()..rrect()..rrect() + ..rrect(color: activeThumbColor), + ); + }); + testWidgets('Switch is opaque when enabled', (WidgetTester tester) async { await tester.pumpWidget( Directionality( @@ -1036,7 +1088,7 @@ void main() { ); }); - testWidgets('Hovering over Cupertino switch updates cursor to clickable on Web', (WidgetTester tester) async { + testWidgets('Hovering over switch updates cursor to clickable on Web', (WidgetTester tester) async { const bool value = false; // Disabled CupertinoSwitch does not update cursor on Web. await tester.pumpWidget( @@ -1060,7 +1112,10 @@ void main() { final Offset cupertinoSwitch = tester.getCenter(find.byType(CupertinoSwitch)); await gesture.addPointer(location: cupertinoSwitch); await tester.pumpAndSettle(); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic + ); // Enabled CupertinoSwitch updates cursor when hovering on Web. await tester.pumpWidget( @@ -1082,7 +1137,10 @@ void main() { await gesture.moveTo(const Offset(10, 10)); await tester.pumpAndSettle(); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic + ); await gesture.moveTo(cupertinoSwitch); await tester.pumpAndSettle(); @@ -1092,6 +1150,46 @@ void main() { ); }); + testWidgets('Switch configures mouse cursor', (WidgetTester tester) async { + const bool value = false; + const Offset switchSize = Offset(51.0, 31.0); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return Center( + child: CupertinoSwitch( + value: value, + dragStartBehavior: DragStartBehavior.down, + mouseCursor: WidgetStateProperty.all(SystemMouseCursors.forbidden), + onChanged: (bool newValue) { }, + ), + ); + }, + ), + ), + ); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + pointer: 1 + ); + // The pointer is not pointing at the switch. + await gesture.addPointer(location: tester.getCenter(find.byType(CupertinoSwitch)) + switchSize); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic + ); + // The pointer now points at the switch. + await gesture.moveTo(tester.getCenter(find.byType(CupertinoSwitch))); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.forbidden + ); + }); + testWidgets('CupertinoSwitch is focusable and has correct focus color', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'CupertinoSwitch'); addTearDown(focusNode.dispose); @@ -1204,4 +1302,636 @@ void main() { expect(focused, isFalse); expect(focusNode.hasFocus, isFalse); }); + + testWidgets('Switch has semantic events', (WidgetTester tester) async { + dynamic semanticEvent; + bool value = false; + tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler(SystemChannels.accessibility, (dynamic message) async { + semanticEvent = message; + }); + final SemanticsTester semanticsTester = SemanticsTester(tester); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return Material( + child: Center( + child: CupertinoSwitch( + value: value, + onChanged: (bool newValue) { + setState(() { + value = newValue; + }); + }, + ), + ), + ); + }, + ), + ), + ); + await tester.tap(find.byType(CupertinoSwitch)); + final RenderObject object = tester.firstRenderObject(find.byType(CupertinoSwitch)); + + expect(value, true); + expect(semanticEvent, { + 'type': 'tap', + 'nodeId': object.debugSemantics!.id, + 'data': {}, + }); + expect(object.debugSemantics!.getSemanticsData().hasAction(SemanticsAction.tap), true); + + semanticsTester.dispose(); + tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler(SystemChannels.accessibility, null); + }); + + testWidgets('Switch sends semantic events from parent if fully merged', (WidgetTester tester) async { + dynamic semanticEvent; + bool value = false; + tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler(SystemChannels.accessibility, (dynamic message) async { + semanticEvent = message; + }); + final SemanticsTester semanticsTester = SemanticsTester(tester); + + await tester.pumpWidget( + CupertinoApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + void onChanged(bool newValue) { + setState(() { + value = newValue; + }); + } + return Material( + child: MergeSemantics( + child: ListTile( + title: const Text('test'), + onTap: () { + onChanged(!value); + }, + trailing: CupertinoSwitch( + value: value, + onChanged: onChanged, + ), + ), + ), + ); + }, + ), + ), + ); + await tester.tap(find.byType(MergeSemantics)); + final RenderObject object = tester.firstRenderObject(find.byType(MergeSemantics)); + + expect(value, true); + expect(semanticEvent, { + 'type': 'tap', + 'nodeId': object.debugSemantics!.id, + 'data': {}, + }); + expect(object.debugSemantics!.getSemanticsData().hasAction(SemanticsAction.tap), true); + + semanticsTester.dispose(); + tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler(SystemChannels.accessibility, null); + }); + + testWidgets('Track outline color resolves in active/enabled states', (WidgetTester tester) async { + const Color activeEnabledTrackOutlineColor = Color(0xFF000001); + const Color activeDisabledTrackOutlineColor = Color(0xFF000002); + const Color inactiveEnabledTrackOutlineColor = Color(0xFF000003); + const Color inactiveDisabledTrackOutlineColor = Color(0xFF000004); + + Color getTrackOutlineColor(Set states) { + if (states.contains(WidgetState.disabled)) { + if (states.contains(WidgetState.selected)) { + return activeDisabledTrackOutlineColor; + } + return inactiveDisabledTrackOutlineColor; + } + if (states.contains(WidgetState.selected)) { + return activeEnabledTrackOutlineColor; + } + return inactiveEnabledTrackOutlineColor; + } + + final WidgetStateProperty trackOutlineColor = WidgetStateColor.resolveWith(getTrackOutlineColor); + + Widget buildSwitch({required bool enabled, required bool active}) { + return Directionality( + textDirection: TextDirection.rtl, + child: CupertinoPageScaffold( + child: Center( + child: CupertinoSwitch( + trackOutlineColor: trackOutlineColor, + value: active, + onChanged: enabled ? (_) { } : null, + ), + ), + ), + ); + } + + await tester.pumpWidget(buildSwitch(enabled: false, active: false)); + + expect( + find.byType(CupertinoSwitch), + paints + ..rrect(style: PaintingStyle.fill) + ..rrect(color: inactiveDisabledTrackOutlineColor, style: PaintingStyle.stroke), + reason: 'Inactive disabled switch track outline should use this value', + ); + + await tester.pumpWidget(buildSwitch(enabled: false, active: true)); + await tester.pumpAndSettle(); + + expect( + find.byType(CupertinoSwitch), + paints + ..rrect(style: PaintingStyle.fill) + ..rrect(color: activeDisabledTrackOutlineColor, style: PaintingStyle.stroke), + reason: 'Active disabled switch track outline should match these colors', + ); + + await tester.pumpWidget(buildSwitch(enabled: true, active: false)); + await tester.pumpAndSettle(); + + expect( + find.byType(CupertinoSwitch), + paints + ..rrect(style: PaintingStyle.fill) + ..rrect(color: inactiveEnabledTrackOutlineColor), + reason: 'Inactive enabled switch track outline should match these colors', + ); + + await tester.pumpWidget(buildSwitch(enabled: true, active: true)); + await tester.pumpAndSettle(); + + expect( + find.byType(CupertinoSwitch), + paints + ..rrect(style: PaintingStyle.fill) + ..rrect(color: activeEnabledTrackOutlineColor), + reason: 'Active enabled switch track outline should match these colors', + ); + }); + + testWidgets('Switch track outline color resolves in hovered/focused states', (WidgetTester tester) async { + final FocusNode focusNode = FocusNode(debugLabel: 'Switch'); + tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + const Color hoveredTrackOutlineColor = Color(0xFF000001); + const Color focusedTrackOutlineColor = Color(0xFF000002); + + Color getTrackOutlineColor(Set states) { + if (states.contains(WidgetState.hovered)) { + return hoveredTrackOutlineColor; + } + if (states.contains(WidgetState.focused)) { + return focusedTrackOutlineColor; + } + return Colors.transparent; + } + + final WidgetStateProperty trackOutlineColor = WidgetStateColor.resolveWith(getTrackOutlineColor); + + Widget buildSwitch() { + return Directionality( + textDirection: TextDirection.rtl, + child: Material( + child: Center( + child: CupertinoSwitch( + focusNode: focusNode, + autofocus: true, + value: true, + trackOutlineColor: trackOutlineColor, + onChanged: (_) { }, + ), + ), + ), + ); + } + + await tester.pumpWidget(buildSwitch()); + await tester.pumpAndSettle(); + expect(focusNode.hasPrimaryFocus, isTrue); + expect( + find.byType(CupertinoSwitch), + paints..rrect(style: PaintingStyle.fill) + ..rrect(color: focusedTrackOutlineColor, style: PaintingStyle.stroke), + reason: 'Active enabled switch track outline should match this color', + ); + + // Start hovering. + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + await gesture.addPointer(); + await gesture.moveTo(tester.getCenter(find.byType(CupertinoSwitch))); + await tester.pumpAndSettle(); + + expect( + find.byType(CupertinoSwitch), + paints + ..rrect(style: PaintingStyle.fill) + ..rrect(color: hoveredTrackOutlineColor, style: PaintingStyle.stroke), + reason: 'Active enabled switch track outline should match this color', + ); + + focusNode.dispose(); + }); + + testWidgets('Track outline width resolves in active/enabled states', (WidgetTester tester) async { + const double activeEnabledTrackOutlineWidth = 1.0; + const double activeDisabledTrackOutlineWidth = 2.0; + const double inactiveEnabledTrackOutlineWidth = 3.0; + const double inactiveDisabledTrackOutlineWidth = 4.0; + + double getTrackOutlineWidth(Set states) { + if (states.contains(WidgetState.disabled)) { + if (states.contains(WidgetState.selected)) { + return activeDisabledTrackOutlineWidth; + } + return inactiveDisabledTrackOutlineWidth; + } + if (states.contains(WidgetState.selected)) { + return activeEnabledTrackOutlineWidth; + } + return inactiveEnabledTrackOutlineWidth; + } + + final WidgetStateProperty trackOutlineWidth = WidgetStateProperty.resolveWith(getTrackOutlineWidth); + const WidgetStateProperty trackOutlineColor = WidgetStatePropertyAll(Color(0xFFFFFFFF)); + + Widget buildSwitch({required bool enabled, required bool active}) { + return CupertinoApp( + home: CupertinoPageScaffold( + child: Center( + child: CupertinoSwitch( + trackOutlineWidth: trackOutlineWidth, + trackOutlineColor: trackOutlineColor, + value: active, + onChanged: enabled ? (_) { } : null, + ), + ), + ), + ); + } + + await tester.pumpWidget(buildSwitch(enabled: false, active: false)); + + expect( + find.byType(CupertinoSwitch), + paints + ..rrect(style: PaintingStyle.fill) + ..rrect(strokeWidth: inactiveDisabledTrackOutlineWidth, style: PaintingStyle.stroke), + reason: 'Inactive disabled switch track outline width should be 4.0', + ); + + await tester.pumpWidget(buildSwitch(enabled: false, active: true)); + await tester.pumpAndSettle(); + + expect( + find.byType(CupertinoSwitch), + paints + ..rrect(style: PaintingStyle.fill) + ..rrect(strokeWidth: activeDisabledTrackOutlineWidth, style: PaintingStyle.stroke), + reason: 'Active disabled switch track outline width should be 2.0', + ); + + await tester.pumpWidget(buildSwitch(enabled: true, active: false)); + await tester.pumpAndSettle(); + + expect( + find.byType(CupertinoSwitch), + paints + ..rrect(style: PaintingStyle.fill) + ..rrect(strokeWidth: inactiveEnabledTrackOutlineWidth, style: PaintingStyle.stroke), + reason: 'Inactive enabled switch track outline width should be 3.0', + ); + + await tester.pumpWidget(buildSwitch(enabled: true, active: true)); + await tester.pumpAndSettle(); + + expect( + find.byType(CupertinoSwitch), + paints + ..rrect(style: PaintingStyle.fill) + ..rrect(strokeWidth: activeEnabledTrackOutlineWidth, style: PaintingStyle.stroke), + reason: 'Active enabled switch track outline width should be 1.0', + ); + }); + + testWidgets('Switch track outline width resolves in hovered/focused states', (WidgetTester tester) async { + final FocusNode focusNode = FocusNode(debugLabel: 'Switch'); + tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + const double hoveredTrackOutlineWidth = 4.0; + const double focusedTrackOutlineWidth = 6.0; + + double getTrackOutlineWidth(Set states) { + if (states.contains(WidgetState.hovered)) { + return hoveredTrackOutlineWidth; + } + if (states.contains(WidgetState.focused)) { + return focusedTrackOutlineWidth; + } + return 8.0; + } + + final WidgetStateProperty trackOutlineWidth = WidgetStateProperty.resolveWith(getTrackOutlineWidth); + const WidgetStateProperty trackOutlineColor = WidgetStatePropertyAll(Color(0xFFFFFFFF)); + + Widget buildSwitch() { + return MaterialApp( + home: Material( + child: Center( + child: CupertinoSwitch( + focusNode: focusNode, + autofocus: true, + value: true, + trackOutlineWidth: trackOutlineWidth, + trackOutlineColor: trackOutlineColor, + onChanged: (_) { }, + ), + ), + ), + ); + } + + await tester.pumpWidget(buildSwitch()); + await tester.pumpAndSettle(); + expect(focusNode.hasPrimaryFocus, isTrue); + expect( + find.byType(CupertinoSwitch), + paints + ..rrect(style: PaintingStyle.fill) + ..rrect(strokeWidth: focusedTrackOutlineWidth, style: PaintingStyle.stroke) + ..rrect(strokeWidth: 3.5, style: PaintingStyle.stroke), + reason: 'Active enabled switch track outline width should be 6.0', + ); + + // Start hovering. + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + await gesture.addPointer(); + await gesture.moveTo(tester.getCenter(find.byType(CupertinoSwitch))); + await tester.pumpAndSettle(); + + expect( + find.byType(CupertinoSwitch), + paints + ..rrect(style: PaintingStyle.fill) + ..rrect(strokeWidth: hoveredTrackOutlineWidth, style: PaintingStyle.stroke), + reason: 'Active enabled switch track outline width should be 4.0', + ); + + focusNode.dispose(); + }); + + testWidgets('Switch can set icon', (WidgetTester tester) async { + WidgetStateProperty thumbIcon(Icon? activeIcon, Icon? inactiveIcon) { + return WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { + return activeIcon; + } + return inactiveIcon; + }); + } + Widget buildSwitch({required bool enabled, required bool active, Icon? activeIcon, Icon? inactiveIcon}) { + return Directionality( + textDirection: TextDirection.ltr, + child: CupertinoPageScaffold( + child: Center( + child: CupertinoSwitch( + thumbIcon: thumbIcon(activeIcon, inactiveIcon), + value: active, + onChanged: enabled ? (_) {} : null, + ), + ), + ), + ); + } + + // The active icon shows when the switch is on. + await tester.pumpWidget(buildSwitch(enabled: true, active: true, activeIcon: const Icon(Icons.close))); + await tester.pumpAndSettle(); + expect( + find.byType(CupertinoSwitch), + paints + ..rrect()..rrect() + ..paragraph(offset: const Offset(31.5, 11.5)), + ); + + // The inactive icon shows when the switch is off. + await tester.pumpWidget(buildSwitch(enabled: true, active: false, inactiveIcon: const Icon(Icons.close))); + await tester.pumpAndSettle(); + expect( + find.byType(CupertinoSwitch), + paints + ..rrect()..rrect()..rrect() + ..paragraph(offset: const Offset(11.5, 11.5)), + ); + + // The active icon doesn't show when the switch is off. + await tester.pumpWidget(buildSwitch(enabled: true, active: false, activeIcon: const Icon(Icons.check))); + await tester.pumpAndSettle(); + expect( + find.byType(CupertinoSwitch), + paints + ..rrect()..rrect()..rrect() + ); + + // The inactive icon doesn't show when the switch is on. + await tester.pumpWidget(buildSwitch(enabled: true, active: true, inactiveIcon: const Icon(Icons.check))); + await tester.pumpAndSettle(); + expect( + find.byType(CupertinoSwitch), + paints + ..rrect()..rrect()..restore(), + ); + + // No icons are shown. + await tester.pumpWidget(buildSwitch(enabled: true, active: false)); + expect( + find.byType(CupertinoSwitch), + paints + ..rrect()..rrect()..rrect()..restore(), + ); + }); + + group('with image', () { + late ui.Image image; + + setUp(() async { + image = await createTestImage(width: 100, height: 100); + }); + + testWidgets('Thumb images show up when set', (WidgetTester tester) async { + imageCache.clear(); + final _TestImageProvider provider1 = _TestImageProvider(); + final _TestImageProvider provider2 = _TestImageProvider(); + + expect(provider1.loadCallCount, 0); + expect(provider2.loadCallCount, 0); + + bool value1 = true; + await tester.pumpWidget( + CupertinoApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return CupertinoPageScaffold( + child: CupertinoSwitch( + activeThumbImage: provider1, + inactiveThumbImage: provider2, + value: value1, + onChanged: (bool val) { + setState(() { + value1 = val; + }); + }, + ), + ); + } + ) + ) + ); + + expect(provider1.loadCallCount, 1); + expect(provider2.loadCallCount, 0); + expect(imageCache.liveImageCount, 1); + await tester.tap(find.byType(CupertinoSwitch)); + await tester.pumpAndSettle(); + expect(provider1.loadCallCount, 1); + expect(provider2.loadCallCount, 1); + expect(imageCache.liveImageCount, 2); + }); + + testWidgets('Does not crash when imageProvider completes after switch is disposed', (WidgetTester tester) async { + final DelayedImageProvider imageProvider = DelayedImageProvider(image); + + await tester.pumpWidget( + CupertinoApp( + home: CupertinoPageScaffold( + child: Center( + child: CupertinoSwitch( + value: true, + onChanged: null, + inactiveThumbImage: imageProvider, + ), + ), + ), + ), + ); + + expect(find.byType(CupertinoSwitch), findsOneWidget); + + // Dispose the switch by taking down the tree. + await tester.pumpWidget(Container()); + expect(find.byType(CupertinoSwitch), findsNothing); + + imageProvider.complete(); + expect(tester.takeException(), isNull); + }); + + testWidgets('Does not crash when previous imageProvider completes after switch is disposed', (WidgetTester tester) async { + final DelayedImageProvider imageProvider1 = DelayedImageProvider(image); + final DelayedImageProvider imageProvider2 = DelayedImageProvider(image); + + Future buildSwitch(ImageProvider imageProvider) { + return tester.pumpWidget( + CupertinoApp( + home: CupertinoPageScaffold( + child: Center( + child: CupertinoSwitch( + value: true, + onChanged: null, + inactiveThumbImage: imageProvider, + ), + ), + ), + ), + ); + } + + await buildSwitch(imageProvider1); + expect(find.byType(CupertinoSwitch), findsOneWidget); + // Replace the ImageProvider. + await buildSwitch(imageProvider2); + expect(find.byType(CupertinoSwitch), findsOneWidget); + + // Dispose the switch by taking down the tree. + await tester.pumpWidget(Container()); + expect(find.byType(CupertinoSwitch), findsNothing); + + // Completing the replaced ImageProvider shouldn't crash. + imageProvider1.complete(); + expect(tester.takeException(), isNull); + + imageProvider2.complete(); + expect(tester.takeException(), isNull); + }); + }); +} + +class _TestImageProvider extends ImageProvider { + _TestImageProvider({ImageStreamCompleter? streamCompleter}) { + _streamCompleter = streamCompleter + ?? OneFrameImageStreamCompleter(_completer.future); + } + + final Completer _completer = Completer(); + late ImageStreamCompleter _streamCompleter; + + bool get loadCalled => _loadCallCount > 0; + int get loadCallCount => _loadCallCount; + int _loadCallCount = 0; + + @override + Future obtainKey(ImageConfiguration configuration) { + return SynchronousFuture<_TestImageProvider>(this); + } + + @override + void resolveStreamForKey(ImageConfiguration configuration, ImageStream stream, Object key, ImageErrorListener handleError) { + super.resolveStreamForKey(configuration, stream, key, handleError); + } + + @override + ImageStreamCompleter loadImage(Object key, ImageDecoderCallback decode) { + _loadCallCount += 1; + return _streamCompleter; + } + + void complete(ui.Image image) { + _completer.complete(ImageInfo(image: image)); + } + + void fail(Object exception, StackTrace? stackTrace) { + _completer.completeError(exception, stackTrace); + } + + @override + String toString() => '${describeIdentity(this)}()'; +} + +class DelayedImageProvider extends ImageProvider { + DelayedImageProvider(this.image); + + final ui.Image image; + + final Completer _completer = Completer(); + + @override + Future obtainKey(ImageConfiguration configuration) { + return SynchronousFuture(this); + } + + @override + ImageStreamCompleter loadImage(DelayedImageProvider key, ImageDecoderCallback decode) { + return OneFrameImageStreamCompleter(_completer.future); + } + + Future complete() async { + _completer.complete(ImageInfo(image: image)); + } + + @override + String toString() => '${describeIdentity(this)}()'; }