switch.dart 68 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'dart:ui';

7
import 'package:flutter/cupertino.dart';
8
import 'package:flutter/foundation.dart';
9
import 'package:flutter/gestures.dart';
10
import 'package:flutter/rendering.dart';
11

12
import 'color_scheme.dart';
13
import 'colors.dart';
14
import 'constants.dart';
15
import 'debug.dart';
16
import 'material_state.dart';
Adam Barth's avatar
Adam Barth committed
17
import 'shadows.dart';
18
import 'switch_theme.dart';
19
import 'theme.dart';
20
import 'theme_data.dart';
21
import 'toggleable.dart';
22

23 24 25 26
// Examples can assume:
// bool _giveVerse = true;
// late StateSetter setState;

27
const double _kSwitchMinSize = kMinInteractiveDimension - 8.0;
28

29 30
enum _SwitchType { material, adaptive }

31
/// A Material Design switch.
32 33 34 35 36 37 38 39
///
/// 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.
///
40 41 42 43 44
/// If the [onChanged] callback is null, then the switch will be disabled (it
/// will not respond to input). A disabled switch's thumb and track are rendered
/// in shades of grey by default. The default appearance of a disabled switch
/// can be overridden with [inactiveThumbColor] and [inactiveTrackColor].
///
45 46
/// Requires one of its ancestors to be a [Material] widget.
///
47 48 49 50
/// Material Design 3 provides the option to add icons on the thumb of the [Switch].
/// If [ThemeData.useMaterial3] is set to true, users can use [Switch.thumbIcon]
/// to add optional Icons based on the different [MaterialState]s of the [Switch].
///
51 52 53 54 55 56 57 58 59 60 61 62 63 64
/// {@tool dartpad}
/// This example shows a toggleable [Switch]. When the thumb slides to the other
/// side of the track, the switch is toggled between on/off.
///
/// ** See code in examples/api/lib/material/switch/switch.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows how to customize [Switch] using [MaterialStateProperty]
/// switch properties.
///
/// ** See code in examples/api/lib/material/switch/switch.1.dart **
/// {@end-tool}
///
65 66 67 68 69 70 71
/// {@tool dartpad}
/// This example shows how to add icons on the thumb of the [Switch] using the
/// [Switch.thumbIcon] property.
///
/// ** See code in examples/api/lib/material/switch/switch.2.dart **
/// {@end-tool}
///
72 73 74 75 76 77 78
/// {@tool dartpad}
/// This example shows how to use the ambient [CupertinoThemeData] to style all
/// widgets which would otherwise use iOS defaults.
///
/// ** See code in examples/api/lib/material/switch/switch.3.dart **
/// {@end-tool}
///
79
/// See also:
80
///
81 82
///  * [SwitchListTile], which combines this widget with a [ListTile] so that
///    you can give the switch a label.
83 84 85
///  * [Checkbox], another widget with similar semantics.
///  * [Radio], for selecting among a set of explicit values.
///  * [Slider], for selecting a value in a range.
86 87
///  * [MaterialStateProperty], an interface for objects that "resolve" to
///    different values depending on a widget's material state.
88
///  * <https://material.io/design/components/selection-controls.html#switches>
89
class Switch extends StatelessWidget {
90
  /// Creates a Material Design switch.
91 92 93 94 95 96
  ///
  /// 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.
  ///
97 98 99 100
  /// 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.
101
  const Switch({
102
    super.key,
103 104
    required this.value,
    required this.onChanged,
105
    this.activeColor,
106 107 108
    this.activeTrackColor,
    this.inactiveThumbColor,
    this.inactiveTrackColor,
109
    this.activeThumbImage,
110
    this.onActiveThumbImageError,
111
    this.inactiveThumbImage,
112
    this.onInactiveThumbImageError,
113 114
    this.thumbColor,
    this.trackColor,
115
    this.trackOutlineColor,
116
    this.trackOutlineWidth,
117
    this.thumbIcon,
118
    this.materialTapTargetSize,
119
    this.dragStartBehavior = DragStartBehavior.start,
120
    this.mouseCursor,
121 122
    this.focusColor,
    this.hoverColor,
123
    this.overlayColor,
124
    this.splashRadius,
125
    this.focusNode,
126
    this.onFocusChange,
127 128
    this.autofocus = false,
  })  : _switchType = _SwitchType.material,
129
        applyCupertinoTheme = false,
130
        assert(activeThumbImage != null || onActiveThumbImageError == null),
131
        assert(inactiveThumbImage != null || onInactiveThumbImageError == null);
132

133 134 135
  /// Creates an adaptive [Switch] based on whether the target platform is iOS
  /// or macOS, following Material design's
  /// [Cross-platform guidelines](https://material.io/design/platform-guidance/cross-platform-adaptation.html).
136
  ///
137 138 139 140 141 142
  /// On iOS and macOS, this constructor creates a [CupertinoSwitch], which has
  /// matching functionality and presentation as Material switches, and are the
  /// graphics expected on iOS. On other platforms, this creates a Material
  /// design [Switch].
  ///
  /// If a [CupertinoSwitch] is created, the following parameters are ignored:
143
  /// [activeTrackColor], [inactiveThumbColor], [inactiveTrackColor], [trackOutlineWidth]
144
  /// [activeThumbImage], [onActiveThumbImageError], [inactiveThumbImage],
145
  /// [onInactiveThumbImageError], [materialTapTargetSize].
146 147 148
  ///
  /// The target platform is based on the current [Theme]: [ThemeData.platform].
  const Switch.adaptive({
149
    super.key,
150 151
    required this.value,
    required this.onChanged,
152 153 154 155 156
    this.activeColor,
    this.activeTrackColor,
    this.inactiveThumbColor,
    this.inactiveTrackColor,
    this.activeThumbImage,
157
    this.onActiveThumbImageError,
158
    this.inactiveThumbImage,
159
    this.onInactiveThumbImageError,
160
    this.materialTapTargetSize,
161 162
    this.thumbColor,
    this.trackColor,
163
    this.trackOutlineColor,
164
    this.trackOutlineWidth,
165
    this.thumbIcon,
166
    this.dragStartBehavior = DragStartBehavior.start,
167
    this.mouseCursor,
168 169
    this.focusColor,
    this.hoverColor,
170
    this.overlayColor,
171
    this.splashRadius,
172
    this.focusNode,
173
    this.onFocusChange,
174
    this.autofocus = false,
175
    this.applyCupertinoTheme,
176
  })  : assert(activeThumbImage != null || onActiveThumbImageError == null),
177
        assert(inactiveThumbImage != null || onInactiveThumbImageError == null),
178
        _switchType = _SwitchType.adaptive;
179

180
  /// Whether this switch is on or off.
181 182
  ///
  /// This property must not be null.
183
  final bool value;
184

185
  /// Called when the user toggles the switch on or off.
186 187 188 189 190 191
  ///
  /// 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
  /// value.
  ///
  /// If null, the switch will be displayed as disabled.
192
  ///
193
  /// The callback provided to [onChanged] should update the state of the parent
194 195 196 197
  /// [StatefulWidget] using the [State.setState] method, so that the parent
  /// gets rebuilt; for example:
  ///
  /// ```dart
198
  /// Switch(
199 200 201 202 203 204
  ///   value: _giveVerse,
  ///   onChanged: (bool newValue) {
  ///     setState(() {
  ///       _giveVerse = newValue;
  ///     });
  ///   },
205
  /// )
206
  /// ```
207
  final ValueChanged<bool>? onChanged;
208

209
  /// {@template flutter.material.switch.activeColor}
210
  /// The color to use when this switch is on.
211
  /// {@endtemplate}
212
  ///
213
  /// Defaults to [ColorScheme.secondary].
214 215 216
  ///
  /// If [thumbColor] returns a non-null color in the [MaterialState.selected]
  /// state, it will be used instead of this color.
217
  final Color? activeColor;
218

219
  /// {@template flutter.material.switch.activeTrackColor}
220
  /// The color to use on the track when this switch is on.
221
  /// {@endtemplate}
222
  ///
223
  /// Defaults to [ColorScheme.secondary] with the opacity set at 50%.
224 225
  ///
  /// Ignored if this switch is created with [Switch.adaptive].
226 227 228
  ///
  /// If [trackColor] returns a non-null color in the [MaterialState.selected]
  /// state, it will be used instead of this color.
229
  final Color? activeTrackColor;
230

231
  /// {@template flutter.material.switch.inactiveThumbColor}
232
  /// The color to use on the thumb when this switch is off.
233
  /// {@endtemplate}
234 235
  ///
  /// Defaults to the colors described in the Material design specification.
236 237
  ///
  /// Ignored if this switch is created with [Switch.adaptive].
238 239 240
  ///
  /// If [thumbColor] returns a non-null color in the default state, it will be
  /// used instead of this color.
241
  final Color? inactiveThumbColor;
242

243
  /// {@template flutter.material.switch.inactiveTrackColor}
244
  /// The color to use on the track when this switch is off.
245
  /// {@endtemplate}
246 247
  ///
  /// Defaults to the colors described in the Material design specification.
248 249
  ///
  /// Ignored if this switch is created with [Switch.adaptive].
250 251 252
  ///
  /// If [trackColor] returns a non-null color in the default state, it will be
  /// used instead of this color.
253
  final Color? inactiveTrackColor;
254

255
  /// {@template flutter.material.switch.activeThumbImage}
256
  /// An image to use on the thumb of this switch when the switch is on.
257
  /// {@endtemplate}
258 259
  ///
  /// Ignored if this switch is created with [Switch.adaptive].
260
  final ImageProvider? activeThumbImage;
261

262
  /// {@template flutter.material.switch.onActiveThumbImageError}
263 264
  /// An optional error callback for errors emitted when loading
  /// [activeThumbImage].
265
  /// {@endtemplate}
266
  final ImageErrorListener? onActiveThumbImageError;
267

268
  /// {@template flutter.material.switch.inactiveThumbImage}
269
  /// An image to use on the thumb of this switch when the switch is off.
270
  /// {@endtemplate}
271 272
  ///
  /// Ignored if this switch is created with [Switch.adaptive].
273
  final ImageProvider? inactiveThumbImage;
274

275
  /// {@template flutter.material.switch.onInactiveThumbImageError}
276 277
  /// An optional error callback for errors emitted when loading
  /// [inactiveThumbImage].
278
  /// {@endtemplate}
279
  final ImageErrorListener? onInactiveThumbImageError;
280

281
  /// {@template flutter.material.switch.thumbColor}
282 283 284 285 286 287 288
  /// The color of this [Switch]'s thumb.
  ///
  /// Resolved in the following states:
  ///  * [MaterialState.selected].
  ///  * [MaterialState.hovered].
  ///  * [MaterialState.focused].
  ///  * [MaterialState.disabled].
289 290 291 292 293 294 295 296 297
  ///
  /// {@tool snippet}
  /// This example resolves the [thumbColor] based on the current
  /// [MaterialState] of the [Switch], providing a different [Color] when it is
  /// [MaterialState.disabled].
  ///
  /// ```dart
  /// Switch(
  ///   value: true,
298
  ///   onChanged: (bool value) { },
299
  ///   thumbColor: MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {
300 301 302 303 304 305 306 307
  ///     if (states.contains(MaterialState.disabled)) {
  ///       return Colors.orange.withOpacity(.48);
  ///     }
  ///     return Colors.orange;
  ///   }),
  /// )
  /// ```
  /// {@end-tool}
308 309 310 311 312 313 314 315 316 317
  /// {@endtemplate}
  ///
  /// If null, then the value of [activeColor] is used in the selected
  /// state and [inactiveThumbColor] in the default state. If that is also null,
  /// then the value of [SwitchThemeData.thumbColor] is used. If that is also
  /// null, then the following colors are used:
  ///
  /// | State    | Light theme                       | Dark theme                        |
  /// |----------|-----------------------------------|-----------------------------------|
  /// | Default  | `Colors.grey.shade50`             | `Colors.grey.shade400`            |
318
  /// | Selected | [ColorScheme.secondary] | [ColorScheme.secondary] |
319
  /// | Disabled | `Colors.grey.shade400`            | `Colors.grey.shade800`            |
320 321
  final MaterialStateProperty<Color?>? thumbColor;

322
  /// {@template flutter.material.switch.trackColor}
323 324 325 326 327 328 329
  /// The color of this [Switch]'s track.
  ///
  /// Resolved in the following states:
  ///  * [MaterialState.selected].
  ///  * [MaterialState.hovered].
  ///  * [MaterialState.focused].
  ///  * [MaterialState.disabled].
330 331 332 333 334 335 336 337 338
  ///
  /// {@tool snippet}
  /// This example resolves the [trackColor] based on the current
  /// [MaterialState] of the [Switch], providing a different [Color] when it is
  /// [MaterialState.disabled].
  ///
  /// ```dart
  /// Switch(
  ///   value: true,
339
  ///   onChanged: (bool value) { },
340
  ///   thumbColor: MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {
341 342 343 344 345 346 347 348
  ///     if (states.contains(MaterialState.disabled)) {
  ///       return Colors.orange.withOpacity(.48);
  ///     }
  ///     return Colors.orange;
  ///   }),
  /// )
  /// ```
  /// {@end-tool}
349 350 351 352 353 354 355 356 357
  /// {@endtemplate}
  ///
  /// If null, then the value of [activeTrackColor] is used in the selected
  /// state and [inactiveTrackColor] in the default state. If that is also null,
  /// then the value of [SwitchThemeData.trackColor] is used. If that is also
  /// null, then the following colors are used:
  ///
  /// | State    | Light theme                     | Dark theme                      |
  /// |----------|---------------------------------|---------------------------------|
358
  /// | Default  | `Color(0x52000000)`             | `Colors.white30`                |
359
  /// | Selected | [activeColor] with alpha `0x80` | [activeColor] with alpha `0x80` |
360
  /// | Disabled | `Colors.black12`                | `Colors.white10`                |
361 362
  final MaterialStateProperty<Color?>? trackColor;

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
  /// {@template flutter.material.switch.trackOutlineColor}
  /// The outline color of this [Switch]'s track.
  ///
  /// Resolved in the following states:
  ///  * [MaterialState.selected].
  ///  * [MaterialState.hovered].
  ///  * [MaterialState.focused].
  ///  * [MaterialState.disabled].
  ///
  /// {@tool snippet}
  /// This example resolves the [trackOutlineColor] based on the current
  /// [MaterialState] of the [Switch], providing a different [Color] when it is
  /// [MaterialState.disabled].
  ///
  /// ```dart
  /// Switch(
  ///   value: true,
380
  ///   onChanged: (bool value) { },
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
  ///   trackOutlineColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {
  ///     if (states.contains(MaterialState.disabled)) {
  ///       return Colors.orange.withOpacity(.48);
  ///     }
  ///     return null; // Use the default color.
  ///   }),
  /// )
  /// ```
  /// {@end-tool}
  /// {@endtemplate}
  ///
  /// In Material 3, the outline color defaults to transparent in the selected
  /// state and [ColorScheme.outline] in the unselected state. In Material 2,
  /// the [Switch] track has no outline by default.
  final MaterialStateProperty<Color?>? trackOutlineColor;

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
  /// {@template flutter.material.switch.trackOutlineWidth}
  /// The outline width of this [Switch]'s track.
  ///
  /// Resolved in the following states:
  ///  * [MaterialState.selected].
  ///  * [MaterialState.hovered].
  ///  * [MaterialState.focused].
  ///  * [MaterialState.disabled].
  ///
  /// {@tool snippet}
  /// This example resolves the [trackOutlineWidth] based on the current
  /// [MaterialState] of the [Switch], providing a different outline width when it is
  /// [MaterialState.disabled].
  ///
  /// ```dart
  /// Switch(
  ///   value: true,
  ///   onChanged: (bool value) { },
  ///   trackOutlineWidth: MaterialStateProperty.resolveWith<double?>((Set<MaterialState> states) {
  ///     if (states.contains(MaterialState.disabled)) {
  ///       return 5.0;
  ///     }
  ///     return null; // Use the default width.
  ///   }),
  /// )
  /// ```
  /// {@end-tool}
  /// {@endtemplate}
  ///
  /// Defaults to 2.0.
  final MaterialStateProperty<double?>? trackOutlineWidth;

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
  /// {@template flutter.material.switch.thumbIcon}
  /// The icon to use on the thumb of this switch
  ///
  /// Resolved in the following states:
  ///  * [MaterialState.selected].
  ///  * [MaterialState.hovered].
  ///  * [MaterialState.focused].
  ///  * [MaterialState.disabled].
  ///
  /// {@tool snippet}
  /// This example resolves the [thumbIcon] based on the current
  /// [MaterialState] of the [Switch], providing a different [Icon] when it is
  /// [MaterialState.disabled].
  ///
  /// ```dart
  /// Switch(
  ///   value: true,
446
  ///   onChanged: (bool value) { },
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
  ///   thumbIcon: MaterialStateProperty.resolveWith<Icon?>((Set<MaterialState> states) {
  ///     if (states.contains(MaterialState.disabled)) {
  ///       return const Icon(Icons.close);
  ///     }
  ///     return null; // All other states will use the default thumbIcon.
  ///   }),
  /// )
  /// ```
  /// {@end-tool}
  /// {@endtemplate}
  ///
  /// If null, then the value of [SwitchThemeData.thumbIcon] is used. If this is also null,
  /// then the [Switch] does not have any icons on the thumb.
  final MaterialStateProperty<Icon?>? thumbIcon;

462
  /// {@template flutter.material.switch.materialTapTargetSize}
463
  /// Configures the minimum size of the tap target.
464
  /// {@endtemplate}
465
  ///
466 467 468
  /// If null, then the value of [SwitchThemeData.materialTapTargetSize] is
  /// used. If that is also null, then the value of
  /// [ThemeData.materialTapTargetSize] is used.
469 470 471
  ///
  /// See also:
  ///
472
  ///  * [MaterialTapTargetSize], for a description of how this affects tap targets.
473
  final MaterialTapTargetSize? materialTapTargetSize;
474

475 476
  final _SwitchType _switchType;

477 478 479
  /// {@macro flutter.cupertino.CupertinoSwitch.applyTheme}
  final bool? applyCupertinoTheme;

480
  /// {@macro flutter.cupertino.CupertinoSwitch.dragStartBehavior}
481 482
  final DragStartBehavior dragStartBehavior;

483
  /// {@template flutter.material.switch.mouseCursor}
484 485 486 487 488 489 490 491 492 493
  /// The cursor for a mouse pointer when it enters or is hovering over the
  /// widget.
  ///
  /// If [mouseCursor] is a [MaterialStateProperty<MouseCursor>],
  /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s:
  ///
  ///  * [MaterialState.selected].
  ///  * [MaterialState.hovered].
  ///  * [MaterialState.focused].
  ///  * [MaterialState.disabled].
494 495 496 497 498 499
  /// {@endtemplate}
  ///
  /// If null, then the value of [SwitchThemeData.mouseCursor] is used. If that
  /// is also null, then [MaterialStateMouseCursor.clickable] is used.
  ///
  /// See also:
500
  ///
501 502 503
  ///  * [MaterialStateMouseCursor], a [MouseCursor] that implements
  ///    `MaterialStateProperty` which is used in APIs that need to accept
  ///    either a [MouseCursor] or a [MaterialStateProperty<MouseCursor>].
504
  final MouseCursor? mouseCursor;
505

506
  /// The color for the button's [Material] when it has the input focus.
507
  ///
508 509 510
  /// If [overlayColor] returns a non-null color in the [MaterialState.focused]
  /// state, it will be used instead.
  ///
511 512 513
  /// If null, then the value of [SwitchThemeData.overlayColor] is used in the
  /// focused state. If that is also null, then the value of
  /// [ThemeData.focusColor] is used.
514
  final Color? focusColor;
515 516

  /// The color for the button's [Material] when a pointer is hovering over it.
517
  ///
518 519 520
  /// If [overlayColor] returns a non-null color in the [MaterialState.hovered]
  /// state, it will be used instead.
  ///
521 522 523
  /// If null, then the value of [SwitchThemeData.overlayColor] is used in the
  /// hovered state. If that is also null, then the value of
  /// [ThemeData.hoverColor] is used.
524
  final Color? hoverColor;
525

526 527 528 529 530 531 532 533 534 535 536 537 538 539
  /// {@template flutter.material.switch.overlayColor}
  /// The color for the switch's [Material].
  ///
  /// Resolves in the following states:
  ///  * [MaterialState.pressed].
  ///  * [MaterialState.selected].
  ///  * [MaterialState.hovered].
  ///  * [MaterialState.focused].
  /// {@endtemplate}
  ///
  /// If null, then the value of [activeColor] with alpha
  /// [kRadialReactionAlpha], [focusColor] and [hoverColor] is used in the
  /// pressed, focused and hovered state. If that is also null,
  /// the value of [SwitchThemeData.overlayColor] is used. If that is
540
  /// also null, then the value of [ColorScheme.secondary] with alpha
541 542 543 544
  /// [kRadialReactionAlpha], [ThemeData.focusColor] and [ThemeData.hoverColor]
  /// is used in the pressed, focused and hovered state.
  final MaterialStateProperty<Color?>? overlayColor;

545
  /// {@template flutter.material.switch.splashRadius}
546
  /// The splash radius of the circular [Material] ink response.
547
  /// {@endtemplate}
548
  ///
549 550
  /// If null, then the value of [SwitchThemeData.splashRadius] is used. If that
  /// is also null, then [kRadialReactionRadius] is used.
551 552
  final double? splashRadius;

553
  /// {@macro flutter.widgets.Focus.focusNode}
554
  final FocusNode? focusNode;
555

556 557 558
  /// {@macro flutter.material.inkwell.onFocusChange}
  final ValueChanged<bool>? onFocusChange;

559 560 561
  /// {@macro flutter.widgets.Focus.autofocus}
  final bool autofocus;

562 563 564
  Size _getSwitchSize(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    final SwitchThemeData switchTheme = SwitchTheme.of(context);
565
    final _SwitchConfig switchConfig = theme.useMaterial3 ? _SwitchConfigM3(context) : _SwitchConfigM2();
566

567
    final MaterialTapTargetSize effectiveMaterialTapTargetSize = materialTapTargetSize
568
      ?? switchTheme.materialTapTargetSize
569 570 571
      ?? theme.materialTapTargetSize;
    switch (effectiveMaterialTapTargetSize) {
      case MaterialTapTargetSize.padded:
572
        return Size(switchConfig.switchWidth, switchConfig.switchHeight);
573
      case MaterialTapTargetSize.shrinkWrap:
574
        return Size(switchConfig.switchWidth, switchConfig.switchHeightCollapsed);
575 576 577 578
    }
  }

  Widget _buildCupertinoSwitch(BuildContext context) {
579
    final Size size = _getSwitchSize(context);
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
    return Container(
      width: size.width, // Same size as the Material switch.
      height: size.height,
      alignment: Alignment.center,
      child: CupertinoSwitch(
        dragStartBehavior: dragStartBehavior,
        value: value,
        onChanged: onChanged,
        activeColor: activeColor,
        trackColor: inactiveTrackColor,
        thumbColor: thumbColor?.resolve(<MaterialState>{}),
        applyTheme: applyCupertinoTheme,
        focusColor: focusColor,
        focusNode: focusNode,
        onFocusChange: onFocusChange,
        autofocus: autofocus,
596 597 598 599 600 601 602 603
      ),
    );
  }

  Widget _buildMaterialSwitch(BuildContext context) {
    return _MaterialSwitch(
      value: value,
      onChanged: onChanged,
604
      size: _getSwitchSize(context),
605 606 607 608 609 610 611 612 613 614
      activeColor: activeColor,
      activeTrackColor: activeTrackColor,
      inactiveThumbColor: inactiveThumbColor,
      inactiveTrackColor: inactiveTrackColor,
      activeThumbImage: activeThumbImage,
      onActiveThumbImageError: onActiveThumbImageError,
      inactiveThumbImage: inactiveThumbImage,
      onInactiveThumbImageError: onInactiveThumbImageError,
      thumbColor: thumbColor,
      trackColor: trackColor,
615
      trackOutlineColor: trackOutlineColor,
616
      trackOutlineWidth: trackOutlineWidth,
617
      thumbIcon: thumbIcon,
618 619 620 621 622 623 624 625
      materialTapTargetSize: materialTapTargetSize,
      dragStartBehavior: dragStartBehavior,
      mouseCursor: mouseCursor,
      focusColor: focusColor,
      hoverColor: hoverColor,
      overlayColor: overlayColor,
      splashRadius: splashRadius,
      focusNode: focusNode,
626
      onFocusChange: onFocusChange,
627 628 629 630
      autofocus: autofocus,
    );
  }

631
  @override
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
  Widget build(BuildContext context) {
    switch (_switchType) {
      case _SwitchType.material:
        return _buildMaterialSwitch(context);

      case _SwitchType.adaptive: {
        final ThemeData theme = Theme.of(context);
        switch (theme.platform) {
          case TargetPlatform.android:
          case TargetPlatform.fuchsia:
          case TargetPlatform.linux:
          case TargetPlatform.windows:
            return _buildMaterialSwitch(context);
          case TargetPlatform.iOS:
          case TargetPlatform.macOS:
            return _buildCupertinoSwitch(context);
        }
      }
    }
  }
652 653

  @override
654 655
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
656 657
    properties.add(FlagProperty('value', value: value, ifTrue: 'on', ifFalse: 'off', showName: true));
    properties.add(ObjectFlagProperty<ValueChanged<bool>>('onChanged', onChanged, ifNull: 'disabled'));
658 659 660
  }
}

661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
class _MaterialSwitch extends StatefulWidget {
  const _MaterialSwitch({
    required this.value,
    required this.onChanged,
    required this.size,
    this.activeColor,
    this.activeTrackColor,
    this.inactiveThumbColor,
    this.inactiveTrackColor,
    this.activeThumbImage,
    this.onActiveThumbImageError,
    this.inactiveThumbImage,
    this.onInactiveThumbImageError,
    this.thumbColor,
    this.trackColor,
676
    this.trackOutlineColor,
677
    this.trackOutlineWidth,
678
    this.thumbIcon,
679 680 681 682 683 684 685 686
    this.materialTapTargetSize,
    this.dragStartBehavior = DragStartBehavior.start,
    this.mouseCursor,
    this.focusColor,
    this.hoverColor,
    this.overlayColor,
    this.splashRadius,
    this.focusNode,
687
    this.onFocusChange,
688
    this.autofocus = false,
689
  })  : assert(activeThumbImage != null || onActiveThumbImageError == null),
690
        assert(inactiveThumbImage != null || onInactiveThumbImageError == null);
691

692 693 694 695 696 697 698 699 700 701 702 703
  final bool value;
  final ValueChanged<bool>? onChanged;
  final Color? activeColor;
  final Color? activeTrackColor;
  final Color? inactiveThumbColor;
  final Color? inactiveTrackColor;
  final ImageProvider? activeThumbImage;
  final ImageErrorListener? onActiveThumbImageError;
  final ImageProvider? inactiveThumbImage;
  final ImageErrorListener? onInactiveThumbImageError;
  final MaterialStateProperty<Color?>? thumbColor;
  final MaterialStateProperty<Color?>? trackColor;
704
  final MaterialStateProperty<Color?>? trackOutlineColor;
705
  final MaterialStateProperty<double?>? trackOutlineWidth;
706
  final MaterialStateProperty<Icon?>? thumbIcon;
707 708 709 710 711 712 713 714
  final MaterialTapTargetSize? materialTapTargetSize;
  final DragStartBehavior dragStartBehavior;
  final MouseCursor? mouseCursor;
  final Color? focusColor;
  final Color? hoverColor;
  final MaterialStateProperty<Color?>? overlayColor;
  final double? splashRadius;
  final FocusNode? focusNode;
715
  final Function(bool)? onFocusChange;
716 717
  final bool autofocus;
  final Size size;
718

719 720 721
  @override
  State<StatefulWidget> createState() => _MaterialSwitchState();
}
722

723 724
class _MaterialSwitchState extends State<_MaterialSwitch> with TickerProviderStateMixin, ToggleableStateMixin {
  final _SwitchPainter _painter = _SwitchPainter();
725

726 727 728 729 730 731 732
  @override
  void didUpdateWidget(_MaterialSwitch oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.value != widget.value) {
      // During a drag we may have modified the curve, reset it if its possible
      // to do without visual discontinuation.
      if (position.value == 0.0 || position.value == 1.0) {
733 734 735 736 737 738 739 740 741
        if (Theme.of(context).useMaterial3) {
          position
            ..curve = Curves.easeOutBack
            ..reverseCurve = Curves.easeOutBack.flipped;
        } else {
          position
            ..curve = Curves.easeIn
            ..reverseCurve = Curves.easeOut;
        }
742 743
      }
      animateToValue();
744 745 746
    }
  }

747 748 749 750
  @override
  void dispose() {
    _painter.dispose();
    super.dispose();
751 752
  }

753 754
  @override
  ValueChanged<bool?>? get onChanged => widget.onChanged != null ? _handleChanged : null;
755

756 757
  @override
  bool get tristate => false;
758

759 760
  @override
  bool? get value => widget.value;
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782

  MaterialStateProperty<Color?> get _widgetThumbColor {
    return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
      if (states.contains(MaterialState.disabled)) {
        return widget.inactiveThumbColor;
      }
      if (states.contains(MaterialState.selected)) {
        return widget.activeColor;
      }
      return widget.inactiveThumbColor;
    });
  }

  MaterialStateProperty<Color?> get _widgetTrackColor {
    return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
      if (states.contains(MaterialState.selected)) {
        return widget.activeTrackColor;
      }
      return widget.inactiveTrackColor;
    });
  }

783 784 785
  double get _trackInnerLength => widget.size.width - _kSwitchMinSize;

  void _handleDragStart(DragStartDetails details) {
786
    if (isInteractive) {
787
      reactionController.forward();
788
    }
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
  }

  void _handleDragUpdate(DragUpdateDetails details) {
    if (isInteractive) {
      position
        ..curve = Curves.linear
        ..reverseCurve = null;
      final double delta = details.primaryDelta! / _trackInnerLength;
      switch (Directionality.of(context)) {
        case TextDirection.rtl:
          positionController.value -= delta;
        case TextDirection.ltr:
          positionController.value += delta;
      }
    }
  }

  bool _needsPositionAnimation = false;

  void _handleDragEnd(DragEndDetails details) {
    if (position.value >= 0.5 != widget.value) {
810
      widget.onChanged?.call(!widget.value);
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
      // Wait with finishing 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();

  }

  void _handleChanged(bool? value) {
    assert(value != null);
    assert(widget.onChanged != null);
826
    widget.onChanged?.call(value!);
827 828 829 830
  }

  @override
  Widget build(BuildContext context) {
831
    assert(debugCheckHasMaterial(context));
832 833 834 835 836 837

    if (_needsPositionAnimation) {
      _needsPositionAnimation = false;
      animateToValue();
    }

838
    final ThemeData theme = Theme.of(context);
839
    final SwitchThemeData switchTheme = SwitchTheme.of(context);
840 841
    final _SwitchConfig switchConfig = theme.useMaterial3 ? _SwitchConfigM3(context) : _SwitchConfigM2();
    final SwitchThemeData defaults = theme.useMaterial3 ? _SwitchDefaultsM3(context) : _SwitchDefaultsM2(context);
842

843 844
    positionController.duration = Duration(milliseconds: switchConfig.toggleDuration);

845 846
    // Colors need to be resolved in selected and non selected states separately
    // so that they can be lerped between.
847 848
    final Set<MaterialState> activeStates = states..add(MaterialState.selected);
    final Set<MaterialState> inactiveStates = states..remove(MaterialState.selected);
849 850

    final Color? activeThumbColor = widget.thumbColor?.resolve(activeStates)
851
      ?? _widgetThumbColor.resolve(activeStates)
852 853 854 855
      ?? switchTheme.thumbColor?.resolve(activeStates);
    final Color effectiveActiveThumbColor = activeThumbColor
      ?? defaults.thumbColor!.resolve(activeStates)!;
    final Color? inactiveThumbColor = widget.thumbColor?.resolve(inactiveStates)
856
      ?? _widgetThumbColor.resolve(inactiveStates)
857 858 859
      ?? switchTheme.thumbColor?.resolve(inactiveStates);
    final Color effectiveInactiveThumbColor = inactiveThumbColor
      ?? defaults.thumbColor!.resolve(inactiveStates)!;
860 861
    final Color effectiveActiveTrackColor = widget.trackColor?.resolve(activeStates)
      ?? _widgetTrackColor.resolve(activeStates)
862
      ?? switchTheme.trackColor?.resolve(activeStates)
863 864
      ?? _widgetThumbColor.resolve(activeStates)?.withAlpha(0x80)
      ?? defaults.trackColor!.resolve(activeStates)!;
865 866 867
    final Color effectiveActiveTrackOutlineColor = widget.trackOutlineColor?.resolve(activeStates)
      ?? switchTheme.trackOutlineColor?.resolve(activeStates)
      ?? Colors.transparent;
868 869 870
    final double? effectiveActiveTrackOutlineWidth = widget.trackOutlineWidth?.resolve(activeStates)
      ?? switchTheme.trackOutlineWidth?.resolve(activeStates)
      ?? defaults.trackOutlineWidth?.resolve(activeStates);
871

872 873
    final Color effectiveInactiveTrackColor = widget.trackColor?.resolve(inactiveStates)
      ?? _widgetTrackColor.resolve(inactiveStates)
874
      ?? switchTheme.trackColor?.resolve(inactiveStates)
875
      ?? defaults.trackColor!.resolve(inactiveStates)!;
876 877 878
    final Color? effectiveInactiveTrackOutlineColor = widget.trackOutlineColor?.resolve(inactiveStates)
      ?? switchTheme.trackOutlineColor?.resolve(inactiveStates)
      ?? defaults.trackOutlineColor?.resolve(inactiveStates);
879 880 881
    final double? effectiveInactiveTrackOutlineWidth = widget.trackOutlineWidth?.resolve(inactiveStates)
      ?? switchTheme.trackOutlineWidth?.resolve(inactiveStates)
      ?? defaults.trackOutlineWidth?.resolve(inactiveStates);
882 883 884 885 886 887 888 889

    final Icon? effectiveActiveIcon = widget.thumbIcon?.resolve(activeStates)
      ?? switchTheme.thumbIcon?.resolve(activeStates);
    final Icon? effectiveInactiveIcon = widget.thumbIcon?.resolve(inactiveStates)
      ?? switchTheme.thumbIcon?.resolve(inactiveStates);

    final Color effectiveActiveIconColor = effectiveActiveIcon?.color ?? switchConfig.iconColor.resolve(activeStates);
    final Color effectiveInactiveIconColor = effectiveInactiveIcon?.color ?? switchConfig.iconColor.resolve(inactiveStates);
890

891
    final Set<MaterialState> focusedStates = states..add(MaterialState.focused);
892 893
    final Color effectiveFocusOverlayColor = widget.overlayColor?.resolve(focusedStates)
      ?? widget.focusColor
894
      ?? switchTheme.overlayColor?.resolve(focusedStates)
895
      ?? defaults.overlayColor!.resolve(focusedStates)!;
896

897
    final Set<MaterialState> hoveredStates = states..add(MaterialState.hovered);
898
    final Color effectiveHoverOverlayColor = widget.overlayColor?.resolve(hoveredStates)
899 900 901
      ?? widget.hoverColor
      ?? switchTheme.overlayColor?.resolve(hoveredStates)
      ?? defaults.overlayColor!.resolve(hoveredStates)!;
902

903
    final Set<MaterialState> activePressedStates = activeStates..add(MaterialState.pressed);
904 905 906 907
    final Color effectiveActivePressedThumbColor = widget.thumbColor?.resolve(activePressedStates)
      ?? _widgetThumbColor.resolve(activePressedStates)
      ?? switchTheme.thumbColor?.resolve(activePressedStates)
      ?? defaults.thumbColor!.resolve(activePressedStates)!;
908
    final Color effectiveActivePressedOverlayColor = widget.overlayColor?.resolve(activePressedStates)
909 910 911
      ?? switchTheme.overlayColor?.resolve(activePressedStates)
      ?? activeThumbColor?.withAlpha(kRadialReactionAlpha)
      ?? defaults.overlayColor!.resolve(activePressedStates)!;
912 913

    final Set<MaterialState> inactivePressedStates = inactiveStates..add(MaterialState.pressed);
914 915 916 917
    final Color effectiveInactivePressedThumbColor = widget.thumbColor?.resolve(inactivePressedStates)
      ?? _widgetThumbColor.resolve(inactivePressedStates)
      ?? switchTheme.thumbColor?.resolve(inactivePressedStates)
      ?? defaults.thumbColor!.resolve(inactivePressedStates)!;
918
    final Color effectiveInactivePressedOverlayColor = widget.overlayColor?.resolve(inactivePressedStates)
919 920 921
      ?? switchTheme.overlayColor?.resolve(inactivePressedStates)
      ?? inactiveThumbColor?.withAlpha(kRadialReactionAlpha)
      ?? defaults.overlayColor!.resolve(inactivePressedStates)!;
922

923 924
    final MaterialStateProperty<MouseCursor> effectiveMouseCursor = MaterialStateProperty.resolveWith<MouseCursor>((Set<MaterialState> states) {
      return MaterialStateProperty.resolveAs<MouseCursor?>(widget.mouseCursor, states)
925
        ?? switchTheme.mouseCursor?.resolve(states)
926 927
        ?? MaterialStateProperty.resolveAs<MouseCursor>(MaterialStateMouseCursor.clickable, states);
    });
928

929 930 931 932 933
    final double effectiveActiveThumbRadius = effectiveActiveIcon == null ? switchConfig.activeThumbRadius : switchConfig.thumbRadiusWithIcon;
    final double effectiveInactiveThumbRadius = effectiveInactiveIcon == null && widget.inactiveThumbImage == null
      ? switchConfig.inactiveThumbRadius : switchConfig.thumbRadiusWithIcon;
    final double effectiveSplashRadius = widget.splashRadius ?? switchTheme.splashRadius ?? defaults.splashRadius!;

934 935 936 937 938 939 940 941 942 943 944
    return Semantics(
      toggled: widget.value,
      child: GestureDetector(
        excludeFromSemantics: true,
        onHorizontalDragStart: _handleDragStart,
        onHorizontalDragUpdate: _handleDragUpdate,
        onHorizontalDragEnd: _handleDragEnd,
        dragStartBehavior: widget.dragStartBehavior,
        child: buildToggleable(
          mouseCursor: effectiveMouseCursor,
          focusNode: widget.focusNode,
945
          onFocusChange: widget.onFocusChange,
946 947 948 949 950 951 952 953 954 955 956
          autofocus: widget.autofocus,
          size: widget.size,
          painter: _painter
            ..position = position
            ..reaction = reaction
            ..reactionFocusFade = reactionFocusFade
            ..reactionHoverFade = reactionHoverFade
            ..inactiveReactionColor = effectiveInactivePressedOverlayColor
            ..reactionColor = effectiveActivePressedOverlayColor
            ..hoverColor = effectiveHoverOverlayColor
            ..focusColor = effectiveFocusOverlayColor
957
            ..splashRadius = effectiveSplashRadius
958 959 960 961 962
            ..downPosition = downPosition
            ..isFocused = states.contains(MaterialState.focused)
            ..isHovered = states.contains(MaterialState.hovered)
            ..activeColor = effectiveActiveThumbColor
            ..inactiveColor = effectiveInactiveThumbColor
963 964
            ..activePressedColor = effectiveActivePressedThumbColor
            ..inactivePressedColor = effectiveInactivePressedThumbColor
965 966 967 968 969
            ..activeThumbImage = widget.activeThumbImage
            ..onActiveThumbImageError = widget.onActiveThumbImageError
            ..inactiveThumbImage = widget.inactiveThumbImage
            ..onInactiveThumbImageError = widget.onInactiveThumbImageError
            ..activeTrackColor = effectiveActiveTrackColor
970
            ..activeTrackOutlineColor = effectiveActiveTrackOutlineColor
971
            ..activeTrackOutlineWidth = effectiveActiveTrackOutlineWidth
972
            ..inactiveTrackColor = effectiveInactiveTrackColor
973
            ..inactiveTrackOutlineColor = effectiveInactiveTrackOutlineColor
974
            ..inactiveTrackOutlineWidth = effectiveInactiveTrackOutlineWidth
975 976 977 978
            ..configuration = createLocalImageConfiguration(context)
            ..isInteractive = isInteractive
            ..trackInnerLength = _trackInnerLength
            ..textDirection = Directionality.of(context)
979 980 981 982
            ..surfaceColor = theme.colorScheme.surface
            ..inactiveThumbRadius = effectiveInactiveThumbRadius
            ..activeThumbRadius = effectiveActiveThumbRadius
            ..pressedThumbRadius = switchConfig.pressedThumbRadius
983
            ..thumbOffset = switchConfig.thumbOffset
984 985 986 987 988 989 990
            ..trackHeight = switchConfig.trackHeight
            ..trackWidth = switchConfig.trackWidth
            ..activeIconColor = effectiveActiveIconColor
            ..inactiveIconColor = effectiveInactiveIconColor
            ..activeIcon = effectiveActiveIcon
            ..inactiveIcon = effectiveInactiveIcon
            ..iconTheme = IconTheme.of(context)
991 992 993
            ..thumbShadow = switchConfig.thumbShadow
            ..transitionalThumbSize = switchConfig.transitionalThumbSize
            ..positionController = positionController,
994
        ),
995 996 997
      ),
    );
  }
998 999
}

1000
class _SwitchPainter extends ToggleablePainter {
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
  AnimationController get positionController => _positionController!;
  AnimationController? _positionController;
  set positionController(AnimationController? value) {
    assert(value != null);
    if (value == _positionController) {
      return;
    }
    _positionController = value;
    notifyListeners();
  }

1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
  Icon? get activeIcon => _activeIcon;
  Icon? _activeIcon;
  set activeIcon(Icon? value) {
    if (value == _activeIcon) {
      return;
    }
    _activeIcon = value;
    notifyListeners();
  }

  Icon? get inactiveIcon => _inactiveIcon;
  Icon? _inactiveIcon;
  set inactiveIcon(Icon? value) {
    if (value == _inactiveIcon) {
      return;
    }
    _inactiveIcon = value;
    notifyListeners();
  }

  IconThemeData? get iconTheme => _iconTheme;
  IconThemeData? _iconTheme;
  set iconTheme(IconThemeData? value) {
    if (value == _iconTheme) {
      return;
    }
    _iconTheme = value;
    notifyListeners();
  }

  Color get activeIconColor => _activeIconColor!;
  Color? _activeIconColor;
  set activeIconColor(Color value) {
    if (value == _activeIconColor) {
      return;
    }
    _activeIconColor = value;
    notifyListeners();
  }

  Color get inactiveIconColor => _inactiveIconColor!;
  Color? _inactiveIconColor;
  set inactiveIconColor(Color value) {
    if (value == _inactiveIconColor) {
      return;
    }
    _inactiveIconColor = value;
    notifyListeners();
  }

1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
  Color get activePressedColor => _activePressedColor!;
  Color? _activePressedColor;
  set activePressedColor(Color? value) {
    assert(value != null);
    if (value == _activePressedColor) {
      return;
    }
    _activePressedColor = value;
    notifyListeners();
  }

  Color get inactivePressedColor => _inactivePressedColor!;
  Color? _inactivePressedColor;
  set inactivePressedColor(Color? value) {
    assert(value != null);
    if (value == _inactivePressedColor) {
      return;
    }
    _inactivePressedColor = value;
    notifyListeners();
  }

1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
  double get activeThumbRadius => _activeThumbRadius!;
  double? _activeThumbRadius;
  set activeThumbRadius(double value) {
    if (value == _activeThumbRadius) {
      return;
    }
    _activeThumbRadius = value;
    notifyListeners();
  }

  double get inactiveThumbRadius => _inactiveThumbRadius!;
  double? _inactiveThumbRadius;
  set inactiveThumbRadius(double value) {
    if (value == _inactiveThumbRadius) {
      return;
    }
    _inactiveThumbRadius = value;
    notifyListeners();
  }

  double get pressedThumbRadius => _pressedThumbRadius!;
  double? _pressedThumbRadius;
  set pressedThumbRadius(double value) {
    if (value == _pressedThumbRadius) {
      return;
    }
    _pressedThumbRadius = value;
    notifyListeners();
  }

1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
  double? get thumbOffset => _thumbOffset;
  double? _thumbOffset;
  set thumbOffset(double? value) {
    if (value == _thumbOffset) {
      return;
    }
    _thumbOffset = value;
    notifyListeners();
  }

  Size get transitionalThumbSize => _transitionalThumbSize!;
  Size? _transitionalThumbSize;
  set transitionalThumbSize(Size value) {
    if (value == _transitionalThumbSize) {
      return;
    }
    _transitionalThumbSize = value;
    notifyListeners();
  }

1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
  double get trackHeight => _trackHeight!;
  double? _trackHeight;
  set trackHeight(double value) {
    if (value == _trackHeight) {
      return;
    }
    _trackHeight = value;
    notifyListeners();
  }

  double get trackWidth => _trackWidth!;
  double? _trackWidth;
  set trackWidth(double value) {
    if (value == _trackWidth) {
      return;
    }
    _trackWidth = value;
    notifyListeners();
  }

1154 1155 1156
  ImageProvider? get activeThumbImage => _activeThumbImage;
  ImageProvider? _activeThumbImage;
  set activeThumbImage(ImageProvider? value) {
1157
    if (value == _activeThumbImage) {
1158
      return;
1159
    }
1160
    _activeThumbImage = value;
1161
    notifyListeners();
1162 1163
  }

1164 1165 1166
  ImageErrorListener? get onActiveThumbImageError => _onActiveThumbImageError;
  ImageErrorListener? _onActiveThumbImageError;
  set onActiveThumbImageError(ImageErrorListener? value) {
1167 1168 1169 1170
    if (value == _onActiveThumbImageError) {
      return;
    }
    _onActiveThumbImageError = value;
1171
    notifyListeners();
1172 1173
  }

1174 1175 1176
  ImageProvider? get inactiveThumbImage => _inactiveThumbImage;
  ImageProvider? _inactiveThumbImage;
  set inactiveThumbImage(ImageProvider? value) {
1177
    if (value == _inactiveThumbImage) {
1178
      return;
1179
    }
1180
    _inactiveThumbImage = value;
1181
    notifyListeners();
1182 1183
  }

1184 1185 1186
  ImageErrorListener? get onInactiveThumbImageError => _onInactiveThumbImageError;
  ImageErrorListener? _onInactiveThumbImageError;
  set onInactiveThumbImageError(ImageErrorListener? value) {
1187 1188 1189 1190
    if (value == _onInactiveThumbImageError) {
      return;
    }
    _onInactiveThumbImageError = value;
1191
    notifyListeners();
1192 1193
  }

1194 1195
  Color get activeTrackColor => _activeTrackColor!;
  Color? _activeTrackColor;
1196
  set activeTrackColor(Color value) {
1197
    if (value == _activeTrackColor) {
1198
      return;
1199
    }
1200
    _activeTrackColor = value;
1201
    notifyListeners();
1202 1203
  }

1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
  Color? get activeTrackOutlineColor => _activeTrackOutlineColor;
  Color? _activeTrackOutlineColor;
  set activeTrackOutlineColor(Color? value) {
    if (value == _activeTrackOutlineColor) {
      return;
    }
    _activeTrackOutlineColor = value;
    notifyListeners();
  }

1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
  Color? get inactiveTrackOutlineColor => _inactiveTrackOutlineColor;
  Color? _inactiveTrackOutlineColor;
  set inactiveTrackOutlineColor(Color? value) {
    if (value == _inactiveTrackOutlineColor) {
      return;
    }
    _inactiveTrackOutlineColor = value;
    notifyListeners();
  }

1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
  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();
  }

1244 1245
  Color get inactiveTrackColor => _inactiveTrackColor!;
  Color? _inactiveTrackColor;
1246
  set inactiveTrackColor(Color value) {
1247
    if (value == _inactiveTrackColor) {
1248
      return;
1249
    }
1250
    _inactiveTrackColor = value;
1251
    notifyListeners();
1252 1253
  }

1254 1255
  ImageConfiguration get configuration => _configuration!;
  ImageConfiguration? _configuration;
1256
  set configuration(ImageConfiguration value) {
1257
    if (value == _configuration) {
1258
      return;
1259
    }
1260
    _configuration = value;
1261
    notifyListeners();
1262 1263
  }

1264 1265
  TextDirection get textDirection => _textDirection!;
  TextDirection? _textDirection;
1266
  set textDirection(TextDirection value) {
1267
    if (_textDirection == value) {
1268
      return;
1269
    }
1270
    _textDirection = value;
1271
    notifyListeners();
1272 1273
  }

1274 1275
  Color get surfaceColor => _surfaceColor!;
  Color? _surfaceColor;
1276
  set surfaceColor(Color value) {
1277
    if (value == _surfaceColor) {
1278
      return;
1279
    }
1280
    _surfaceColor = value;
1281
    notifyListeners();
1282 1283
  }

1284 1285 1286 1287 1288
  bool get isInteractive => _isInteractive!;
  bool? _isInteractive;
  set isInteractive(bool value) {
    if (value == _isInteractive) {
      return;
1289
    }
1290 1291
    _isInteractive = value;
    notifyListeners();
1292 1293
  }

1294 1295 1296 1297 1298
  double get trackInnerLength => _trackInnerLength!;
  double? _trackInnerLength;
  set trackInnerLength(double value) {
    if (value == _trackInnerLength) {
      return;
1299
    }
1300 1301
    _trackInnerLength = value;
    notifyListeners();
1302 1303
  }

1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
  List<BoxShadow>? get thumbShadow => _thumbShadow;
  List<BoxShadow>? _thumbShadow;
  set thumbShadow(List<BoxShadow>? value) {
    if (value == _thumbShadow) {
      return;
    }
    _thumbShadow = value;
    notifyListeners();
  }

1314 1315 1316 1317
  Color? _cachedThumbColor;
  ImageProvider? _cachedThumbImage;
  ImageErrorListener? _cachedThumbErrorListener;
  BoxPainter? _cachedThumbPainter;
1318

1319 1320
  ShapeDecoration _createDefaultThumbDecoration(Color color, ImageProvider? image, ImageErrorListener? errorListener) {
    return ShapeDecoration(
1321
      color: color,
1322
      image: image == null ? null : DecorationImage(image: image, onError: errorListener),
1323 1324
      shape: const StadiumBorder(),
      shadows: thumbShadow,
1325 1326
    );
  }
1327

1328 1329 1330 1331 1332 1333 1334
  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).
1335
    if (!_isPainting) {
1336
      notifyListeners();
1337
    }
1338 1339
  }

1340 1341 1342 1343
  bool _stopPressAnimation = false;
  double? _pressedInactiveThumbRadius;
  double? _pressedActiveThumbRadius;

1344
  @override
1345
  void paint(Canvas canvas, Size size) {
1346 1347
    final double currentValue = position.value;

1348
    final double visualPosition;
1349 1350 1351 1352 1353 1354
    switch (textDirection) {
      case TextDirection.rtl:
        visualPosition = 1.0 - currentValue;
      case TextDirection.ltr:
        visualPosition = currentValue;
    }
1355
    if (reaction.status == AnimationStatus.reverse && !_stopPressAnimation) {
1356 1357 1358 1359 1360 1361 1362 1363
      _stopPressAnimation = true;
    } else {
      _stopPressAnimation = false;
    }

    // To get the thumb radius when the press ends, the value can be any number
    // between activeThumbRadius/inactiveThumbRadius and pressedThumbRadius.
    if (!_stopPressAnimation) {
1364
      if (reaction.isCompleted) {
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
        // This happens when the thumb is dragged instead of being tapped.
        _pressedInactiveThumbRadius = lerpDouble(inactiveThumbRadius, pressedThumbRadius, reaction.value);
        _pressedActiveThumbRadius = lerpDouble(activeThumbRadius, pressedThumbRadius, reaction.value);
      }
      if (currentValue == 0) {
        _pressedInactiveThumbRadius = lerpDouble(inactiveThumbRadius, pressedThumbRadius, reaction.value);
        _pressedActiveThumbRadius = activeThumbRadius;
      }
      if (currentValue == 1) {
        _pressedActiveThumbRadius = lerpDouble(activeThumbRadius, pressedThumbRadius, reaction.value);
        _pressedInactiveThumbRadius = inactiveThumbRadius;
      }
    }

    final Size inactiveThumbSize = Size.fromRadius(_pressedInactiveThumbRadius ?? inactiveThumbRadius);
    final Size activeThumbSize = Size.fromRadius(_pressedActiveThumbRadius ?? activeThumbRadius);
    Animation<Size> thumbSizeAnimation(bool isForward) {
      List<TweenSequenceItem<Size>> thumbSizeSequence;
      if (isForward) {
        thumbSizeSequence = <TweenSequenceItem<Size>>[
          TweenSequenceItem<Size>(
            tween: Tween<Size>(begin: inactiveThumbSize, end: transitionalThumbSize)
                .chain(CurveTween(curve: const Cubic(0.31, 0.00, 0.56, 1.00))),
            weight: 11,
          ),
          TweenSequenceItem<Size>(
            tween: Tween<Size>(begin: transitionalThumbSize, end: activeThumbSize)
                .chain(CurveTween(curve: const Cubic(0.20, 0.00, 0.00, 1.00))),
            weight: 72,
          ),
          TweenSequenceItem<Size>(
            tween: ConstantTween<Size>(activeThumbSize),
            weight: 17,
          )
        ];
      } else {
        thumbSizeSequence = <TweenSequenceItem<Size>>[
          TweenSequenceItem<Size>(
            tween: ConstantTween<Size>(inactiveThumbSize),
            weight: 17,
          ),
          TweenSequenceItem<Size>(
            tween: Tween<Size>(begin: inactiveThumbSize, end: transitionalThumbSize)
                .chain(CurveTween(curve: const Cubic(0.20, 0.00, 0.00, 1.00).flipped)),
            weight: 72,
          ),
          TweenSequenceItem<Size>(
            tween: Tween<Size>(begin: transitionalThumbSize, end: activeThumbSize)
                .chain(CurveTween(curve: const Cubic(0.31, 0.00, 0.56, 1.00).flipped)),
            weight: 11,
          ),
        ];
      }

      return TweenSequence<Size>(thumbSizeSequence).animate(positionController);
    }

    Size thumbSize;
1423
    if (reaction.isCompleted) {
1424 1425
      thumbSize = Size.fromRadius(pressedThumbRadius);
    } else {
1426
      if (position.isDismissed || position.status == AnimationStatus.forward) {
1427 1428 1429 1430 1431 1432 1433 1434 1435
        thumbSize = thumbSizeAnimation(true).value;
      } else {
        thumbSize = thumbSizeAnimation(false).value;
      }
    }

    // The thumb contracts slightly during the animation in Material 2.
    final double inset = thumbOffset == null ? 0 : 1.0 - (currentValue - thumbOffset!).abs() * 2.0;
    thumbSize = Size(thumbSize.width - inset, thumbSize.height - inset);
1436

1437 1438
    final double colorValue = CurvedAnimation(parent: positionController, curve: Curves.easeOut, reverseCurve: Curves.easeIn).value;
    final Color trackColor = Color.lerp(inactiveTrackColor, activeTrackColor, colorValue)!;
1439
    final Color? trackOutlineColor = inactiveTrackOutlineColor == null ? null
1440
        : Color.lerp(inactiveTrackOutlineColor, activeTrackOutlineColor, colorValue);
1441
    final double? trackOutlineWidth = lerpDouble(inactiveTrackOutlineWidth, activeTrackOutlineWidth, colorValue);
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
    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)!;
    }

1453 1454 1455 1456
    // 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);
1457

1458 1459 1460
    final Icon? thumbIcon = currentValue < 0.5 ? inactiveIcon : activeIcon;

    final ImageProvider? thumbImage = currentValue < 0.5 ? inactiveThumbImage : activeThumbImage;
1461

1462
    final ImageErrorListener? thumbErrorListener = currentValue < 0.5 ? onInactiveThumbImageError : onActiveThumbImageError;
1463

1464
    final Paint paint = Paint()
1465
      ..color = trackColor;
1466

1467
    final Offset trackPaintOffset = _computeTrackPaintOffset(size, trackWidth, trackHeight);
1468 1469
    final Offset thumbPaintOffset = _computeThumbPaintOffset(trackPaintOffset, thumbSize, visualPosition);
    final Offset radialReactionOrigin = Offset(thumbPaintOffset.dx + thumbSize.height / 2, size.height / 2);
1470

1471
    _paintTrackWith(canvas, paint, trackPaintOffset, trackOutlineColor, trackOutlineWidth);
1472 1473 1474 1475
    paintRadialReaction(canvas: canvas, origin: radialReactionOrigin);
    _paintThumbWith(
      thumbPaintOffset,
      canvas,
1476
      colorValue,
1477 1478 1479
      thumbColor,
      thumbImage,
      thumbErrorListener,
1480
      thumbIcon,
1481 1482
      thumbSize,
      inset,
1483 1484 1485 1486 1487
    );
  }

  /// Computes canvas offset for track's upper left corner
  Offset _computeTrackPaintOffset(Size canvasSize, double trackWidth, double trackHeight) {
1488 1489
    final double horizontalOffset = (canvasSize.width - trackWidth) / 2.0;
    final double verticalOffset = (canvasSize.height - trackHeight) / 2.0;
1490 1491 1492 1493 1494 1495

    return Offset(horizontalOffset, verticalOffset);
  }

  /// Computes canvas offset for thumb's upper left corner as if it were a
  /// square
1496
  Offset _computeThumbPaintOffset(Offset trackPaintOffset, Size thumbSize, double visualPosition) {
1497
    // How much thumb radius extends beyond the track
1498
    final double trackRadius = trackHeight / 2;
1499 1500
    final double additionalThumbRadius = thumbSize.height / 2 - trackRadius;
    final double additionalRectWidth = (thumbSize.width - thumbSize.height) / 2;
1501 1502

    final double horizontalProgress = visualPosition * trackInnerLength;
1503
    final double thumbHorizontalOffset = trackPaintOffset.dx - additionalThumbRadius - additionalRectWidth + horizontalProgress;
1504 1505 1506 1507 1508
    final double thumbVerticalOffset = trackPaintOffset.dy - additionalThumbRadius;

    return Offset(thumbHorizontalOffset, thumbVerticalOffset);
  }

1509
  void _paintTrackWith(Canvas canvas, Paint paint, Offset trackPaintOffset, Color? trackOutlineColor, double? trackOutlineWidth) {
1510
    final Rect trackRect = Rect.fromLTWH(
1511 1512
      trackPaintOffset.dx,
      trackPaintOffset.dy,
1513 1514
      trackWidth,
      trackHeight,
1515
    );
1516
    final double trackRadius = trackHeight / 2;
1517 1518
    final RRect trackRRect = RRect.fromRectAndRadius(
      trackRect,
1519
      Radius.circular(trackRadius),
1520
    );
1521

1522
    canvas.drawRRect(trackRRect, paint);
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537

    if (trackOutlineColor != null) {
      // paint track outline
      final Rect outlineTrackRect = Rect.fromLTWH(
        trackPaintOffset.dx + 1,
        trackPaintOffset.dy + 1,
        trackWidth - 2,
        trackHeight - 2,
      );
      final RRect outlineTrackRRect = RRect.fromRectAndRadius(
        outlineTrackRect,
        Radius.circular(trackRadius),
      );
      final Paint outlinePaint = Paint()
        ..style = PaintingStyle.stroke
1538
        ..strokeWidth = trackOutlineWidth ?? 2.0
1539 1540 1541
        ..color = trackOutlineColor;
      canvas.drawRRect(outlineTrackRRect, outlinePaint);
    }
1542
  }
1543

1544
  void _paintThumbWith(
1545 1546 1547 1548 1549 1550 1551
      Offset thumbPaintOffset,
      Canvas canvas,
      double currentValue,
      Color thumbColor,
      ImageProvider? thumbImage,
      ImageErrorListener? thumbErrorListener,
      Icon? thumbIcon,
1552 1553
      Size thumbSize,
      double inset,
1554
      ) {
1555 1556
    try {
      _isPainting = true;
1557
      if (_cachedThumbPainter == null || thumbColor != _cachedThumbColor || thumbImage != _cachedThumbImage || thumbErrorListener != _cachedThumbErrorListener) {
1558
        _cachedThumbColor = thumbColor;
1559
        _cachedThumbImage = thumbImage;
1560
        _cachedThumbErrorListener = thumbErrorListener;
1561
        _cachedThumbPainter?.dispose();
1562
        _cachedThumbPainter = _createDefaultThumbDecoration(thumbColor, thumbImage, thumbErrorListener).createBoxPainter(_handleDecorationChanged);
1563
      }
1564
      final BoxPainter thumbPainter = _cachedThumbPainter!;
1565

1566 1567
      thumbPainter.paint(
        canvas,
1568
        thumbPaintOffset,
1569
        configuration.copyWith(size: thumbSize),
1570
      );
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603

      if (thumbIcon != null && thumbIcon.icon != null) {
        final Color iconColor = Color.lerp(inactiveIconColor, activeIconColor, currentValue)!;
        final double iconSize = thumbIcon.size ?? _SwitchConfigM3.iconSize;
        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<Shadow>? iconShadows = thumbIcon.shadows ?? iconTheme?.shadows;

        final TextSpan textSpan = TextSpan(
          text: String.fromCharCode(iconData.codePoint),
          style: TextStyle(
            fontVariations: <FontVariation>[
              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,
          ),
        );
        final TextPainter textPainter = TextPainter(
          textDirection: textDirection,
          text: textSpan,
        );
        textPainter.layout();
1604 1605 1606
        final double additionalHorizontalOffset = (thumbSize.width - iconSize) / 2;
        final double additionalVerticalOffset = (thumbSize.height - iconSize) / 2;
        final Offset offset = thumbPaintOffset + Offset(additionalHorizontalOffset, additionalVerticalOffset);
1607 1608 1609

        textPainter.paint(canvas, offset);
      }
1610 1611 1612
    } finally {
      _isPainting = false;
    }
1613
  }
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623

  @override
  void dispose() {
    _cachedThumbPainter?.dispose();
    _cachedThumbPainter = null;
    _cachedThumbColor = null;
    _cachedThumbImage = null;
    _cachedThumbErrorListener = null;
    super.dispose();
  }
1624
}
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637

mixin _SwitchConfig {
  double get trackHeight;
  double get trackWidth;
  double get switchWidth;
  double get switchHeight;
  double get switchHeightCollapsed;
  double get activeThumbRadius;
  double get inactiveThumbRadius;
  double get pressedThumbRadius;
  double get thumbRadiusWithIcon;
  List<BoxShadow>? get thumbShadow;
  MaterialStateProperty<Color> get iconColor;
1638 1639 1640
  double? get thumbOffset;
  Size get transitionalThumbSize;
  int get toggleDuration;
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
}

// Hand coded defaults based on Material Design 2.
class _SwitchConfigM2 with _SwitchConfig {
    _SwitchConfigM2();

  @override
  double get activeThumbRadius => 10.0;

  @override
  MaterialStateProperty<Color> get iconColor => MaterialStateProperty.all<Color>(Colors.transparent);

  @override
  double get inactiveThumbRadius => 10.0;

  @override
  double get pressedThumbRadius => 10.0;

  @override
  double get switchHeight => _kSwitchMinSize + 8.0;

  @override
  double get switchHeightCollapsed => _kSwitchMinSize;

  @override
  double get switchWidth => trackWidth - 2 * (trackHeight / 2.0) + _kSwitchMinSize;

  @override
  double get thumbRadiusWithIcon => 10.0;

  @override
  List<BoxShadow>? get thumbShadow => kElevationToShadow[1];

  @override
  double get trackHeight => 14.0;

  @override
  double get trackWidth => 33.0;
1679 1680 1681 1682 1683 1684 1685 1686 1687

  @override
  double get thumbOffset => 0.5;

  @override
  Size get transitionalThumbSize => const Size(20, 20);

  @override
  int get toggleDuration => 200;
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
}

class _SwitchDefaultsM2 extends SwitchThemeData {
  _SwitchDefaultsM2(BuildContext context)
      : _theme = Theme.of(context),
        _colors = Theme.of(context).colorScheme;

  final ThemeData _theme;
  final ColorScheme _colors;

  @override
  MaterialStateProperty<Color> get thumbColor {
    final bool isDark = _theme.brightness == Brightness.dark;

    return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
      if (states.contains(MaterialState.disabled)) {
        return isDark ? Colors.grey.shade800 : Colors.grey.shade400;
      }
      if (states.contains(MaterialState.selected)) {
        return _colors.secondary;
      }
      return isDark ? Colors.grey.shade400 : Colors.grey.shade50;
    });
  }

  @override
  MaterialStateProperty<Color> get trackColor {
    final bool isDark = _theme.brightness == Brightness.dark;
    const Color black32 = Color(0x52000000); // Black with 32% opacity

    return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
      if (states.contains(MaterialState.disabled)) {
        return isDark ? Colors.white10 : Colors.black12;
      }
      if (states.contains(MaterialState.selected)) {
        final Color activeColor = _colors.secondary;
        return activeColor.withAlpha(0x80);
      }
      return isDark ? Colors.white30 : black32;
    });
  }

1730 1731 1732
  @override
  MaterialStateProperty<Color?>? get trackOutlineColor => null;

1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
  @override
  MaterialTapTargetSize get materialTapTargetSize => _theme.materialTapTargetSize;

  @override
  MaterialStateProperty<MouseCursor> get mouseCursor =>
    MaterialStateProperty.resolveWith((Set<MaterialState> states) => MaterialStateMouseCursor.clickable.resolve(states));

  @override
  MaterialStateProperty<Color?> get overlayColor {
    return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
      if (states.contains(MaterialState.pressed)) {
        return thumbColor.resolve(states).withAlpha(kRadialReactionAlpha);
      }
      if (states.contains(MaterialState.hovered)) {
        return _theme.hoverColor;
      }
1749 1750 1751
      if (states.contains(MaterialState.focused)) {
        return _theme.focusColor;
      }
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
      return null;
    });
  }

  @override
  double get splashRadius => kRadialReactionRadius;
}

// BEGIN GENERATED TOKEN PROPERTIES - Switch

// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
//   dev/tools/gen_defaults/bin/gen_defaults.dart.

class _SwitchDefaultsM3 extends SwitchThemeData {
1768
  _SwitchDefaultsM3(this.context);
1769

1770 1771
  final BuildContext context;
  late final ColorScheme _colors = Theme.of(context).colorScheme;
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840

  @override
  MaterialStateProperty<Color> get thumbColor {
    return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
      if (states.contains(MaterialState.disabled)) {
        if (states.contains(MaterialState.selected)) {
          return _colors.surface.withOpacity(1.0);
        }
        return _colors.onSurface.withOpacity(0.38);
      }
      if (states.contains(MaterialState.selected)) {
        if (states.contains(MaterialState.pressed)) {
          return _colors.primaryContainer;
        }
        if (states.contains(MaterialState.hovered)) {
          return _colors.primaryContainer;
        }
        if (states.contains(MaterialState.focused)) {
          return _colors.primaryContainer;
        }
        return _colors.onPrimary;
      }
      if (states.contains(MaterialState.pressed)) {
        return _colors.onSurfaceVariant;
      }
      if (states.contains(MaterialState.hovered)) {
        return _colors.onSurfaceVariant;
      }
      if (states.contains(MaterialState.focused)) {
        return _colors.onSurfaceVariant;
      }
      return _colors.outline;
    });
  }

  @override
  MaterialStateProperty<Color> get trackColor {
    return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
      if (states.contains(MaterialState.disabled)) {
        if (states.contains(MaterialState.selected)) {
          return _colors.onSurface.withOpacity(0.12);
        }
        return _colors.surfaceVariant.withOpacity(0.12);
      }
      if (states.contains(MaterialState.selected)) {
        if (states.contains(MaterialState.pressed)) {
          return _colors.primary;
        }
        if (states.contains(MaterialState.hovered)) {
          return _colors.primary;
        }
        if (states.contains(MaterialState.focused)) {
          return _colors.primary;
        }
        return _colors.primary;
      }
      if (states.contains(MaterialState.pressed)) {
        return _colors.surfaceVariant;
      }
      if (states.contains(MaterialState.hovered)) {
        return _colors.surfaceVariant;
      }
      if (states.contains(MaterialState.focused)) {
        return _colors.surfaceVariant;
      }
      return _colors.surfaceVariant;
    });
  }

1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
  @override
  MaterialStateProperty<Color?> get trackOutlineColor {
    return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
      if (states.contains(MaterialState.selected)) {
        return Colors.transparent;
      }
      if (states.contains(MaterialState.disabled)) {
        return _colors.onSurface.withOpacity(0.12);
      }
      return _colors.outline;
    });
  }

1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
  @override
  MaterialStateProperty<Color?> get overlayColor {
    return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
      if (states.contains(MaterialState.selected)) {
        if (states.contains(MaterialState.pressed)) {
          return _colors.primary.withOpacity(0.12);
        }
        if (states.contains(MaterialState.hovered)) {
          return _colors.primary.withOpacity(0.08);
        }
        if (states.contains(MaterialState.focused)) {
          return _colors.primary.withOpacity(0.12);
        }
        return null;
      }
      if (states.contains(MaterialState.pressed)) {
        return _colors.onSurface.withOpacity(0.12);
      }
      if (states.contains(MaterialState.hovered)) {
        return _colors.onSurface.withOpacity(0.08);
      }
      if (states.contains(MaterialState.focused)) {
        return _colors.onSurface.withOpacity(0.12);
      }
      return null;
    });
  }

1882 1883 1884
  @override
  MaterialStatePropertyAll<double> get trackOutlineWidth => const MaterialStatePropertyAll<double>(2.0);

1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
  @override
  double get splashRadius => 40.0 / 2;
}

class _SwitchConfigM3 with _SwitchConfig {
  _SwitchConfigM3(this.context)
    : _colors = Theme.of(context).colorScheme;

  BuildContext context;
  final ColorScheme _colors;

  static const double iconSize = 16.0;

  @override
  double get activeThumbRadius => 24.0 / 2;

  @override
  MaterialStateProperty<Color> get iconColor {
    return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
      if (states.contains(MaterialState.disabled)) {
        if (states.contains(MaterialState.selected)) {
          return _colors.onSurface.withOpacity(0.38);
        }
        return _colors.surfaceVariant.withOpacity(0.38);
      }
      if (states.contains(MaterialState.selected)) {
        if (states.contains(MaterialState.pressed)) {
          return _colors.onPrimaryContainer;
        }
        if (states.contains(MaterialState.hovered)) {
          return _colors.onPrimaryContainer;
        }
        if (states.contains(MaterialState.focused)) {
          return _colors.onPrimaryContainer;
        }
        return _colors.onPrimaryContainer;
      }
      if (states.contains(MaterialState.pressed)) {
        return _colors.surfaceVariant;
      }
      if (states.contains(MaterialState.hovered)) {
        return _colors.surfaceVariant;
      }
      if (states.contains(MaterialState.focused)) {
        return _colors.surfaceVariant;
      }
      return _colors.surfaceVariant;
    });
  }

  @override
  double get inactiveThumbRadius => 16.0 / 2;

  @override
  double get pressedThumbRadius => 28.0 / 2;

  @override
  double get switchHeight => _kSwitchMinSize + 8.0;

  @override
  double get switchHeightCollapsed => _kSwitchMinSize;

  @override
  double get switchWidth => trackWidth - 2 * (trackHeight / 2.0) + _kSwitchMinSize;

  @override
  double get thumbRadiusWithIcon => 24.0 / 2;

  @override
  List<BoxShadow>? get thumbShadow => kElevationToShadow[0];

  @override
  double get trackHeight => 32.0;

  @override
  double get trackWidth => 52.0;
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972

  // The thumb size at the middle of the track. Hand coded default based on the animation specs.
  @override
  Size get transitionalThumbSize => const Size(34, 22);

  // Hand coded default based on the animation specs.
  @override
  int get toggleDuration => 300;

  // Hand coded default based on the animation specs.
  @override
  double? get thumbOffset => null;
1973 1974 1975
}

// END GENERATED TOKEN PROPERTIES - Switch