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

import 'package:flutter/widgets.dart';

import 'list_tile.dart';
import 'switch.dart';
import 'theme.dart';
10
import 'theme_data.dart';
11

12 13
// Examples can assume:
// void setState(VoidCallback fn) { }
14
// bool _isSelected;
15

16 17
enum _SwitchListTileType { material, adaptive }

18 19
/// A [ListTile] with a [Switch]. In other words, a switch with a label.
///
20 21
/// {@youtube 560 315 https://www.youtube.com/watch?v=0igIjvtEWNU}
///
22
/// The entire list tile is interactive: tapping anywhere in the tile toggles
23 24 25 26 27 28
/// the switch. Tapping and dragging the [Switch] also triggers the [onChanged]
/// callback.
///
/// To ensure that [onChanged] correctly triggers, the state passed
/// into [value] must be properly managed. This is typically done by invoking
/// [State.setState] in [onChanged] to toggle the state value.
29 30 31 32 33 34 35 36 37
///
/// The [value], [onChanged], [activeColor], [activeThumbImage], and
/// [inactiveThumbImage] properties of this widget are identical to the
/// similarly-named properties on the [Switch] widget.
///
/// The [title], [subtitle], [isThreeLine], and [dense] properties are like
/// those of the same name on [ListTile].
///
/// The [selected] property on this widget is similar to the [ListTile.selected]
38 39 40 41 42 43
/// property. This tile's [activeColor] is used for the selected item's text color, or
/// the theme's [ThemeData.toggleableActiveColor] if [activeColor] is null.
///
/// This widget does not coordinate the [selected] state and the
/// [value]; to have the list tile appear selected when the
/// switch button is on, use the same value for both.
44 45
///
/// The switch is shown on the right by default in left-to-right languages (i.e.
46 47
/// in the [ListTile.trailing] slot) which can be changed using [controlAffinity].
/// The [secondary] widget is placed in the [ListTile.leading] slot.
48
///
49 50 51
/// To show the [SwitchListTile] as disabled, pass null as the [onChanged]
/// callback.
///
52
/// {@tool dartpad --template=stateful_widget_scaffold_center}
53 54
///
/// ![SwitchListTile sample](https://flutter.github.io/assets-for-api-docs/assets/material/switch_list_tile.png)
55 56 57 58 59
///
/// This widget shows a switch that, when toggled, changes the state of a [bool]
/// member field called `_lights`.
///
/// ```dart
60 61
/// bool _lights = false;
///
62
/// @override
63
/// Widget build(BuildContext context) {
64 65 66 67 68
///   return SwitchListTile(
///     title: const Text('Lights'),
///     value: _lights,
///     onChanged: (bool value) { setState(() { _lights = value; }); },
///     secondary: const Icon(Icons.lightbulb_outline),
69 70
///   );
/// }
71
/// ```
72
/// {@end-tool}
73
///
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
/// ## Semantics in SwitchListTile
///
/// Since the entirety of the SwitchListTile is interactive, it should represent
/// itself as a single interactive entity.
///
/// To do so, a SwitchListTile widget wraps its children with a [MergeSemantics]
/// widget. [MergeSemantics] will attempt to merge its descendant [Semantics]
/// nodes into one node in the semantics tree. Therefore, SwitchListTile will
/// throw an error if any of its children requires its own [Semantics] node.
///
/// For example, you cannot nest a [RichText] widget as a descendant of
/// SwitchListTile. [RichText] has an embedded gesture recognizer that
/// requires its own [Semantics] node, which directly conflicts with
/// SwitchListTile's desire to merge all its descendants' semantic nodes
/// into one. Therefore, it may be necessary to create a custom radio tile
/// widget to accommodate similar use cases.
///
91
/// {@tool dartpad --template=stateful_widget_scaffold_center}
92 93 94 95 96 97 98 99 100 101 102 103 104
///
/// ![Switch list tile semantics sample](https://flutter.github.io/assets-for-api-docs/assets/material/switch_list_tile_semantics.png)
///
/// Here is an example of a custom labeled radio widget, called
/// LinkedLabelRadio, that includes an interactive [RichText] widget that
/// handles tap gestures.
///
/// ```dart imports
/// import 'package:flutter/gestures.dart';
/// ```
/// ```dart preamble
/// class LinkedLabelSwitch extends StatelessWidget {
///   const LinkedLabelSwitch({
105
///     Key? key,
106 107 108 109
///     required this.label,
///     required this.padding,
///     required this.value,
///     required this.onChanged,
110
///   }) : super(key: key);
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
///
///   final String label;
///   final EdgeInsets padding;
///   final bool value;
///   final Function onChanged;
///
///   @override
///   Widget build(BuildContext context) {
///     return Padding(
///       padding: padding,
///       child: Row(
///         children: <Widget>[
///           Expanded(
///             child: RichText(
///               text: TextSpan(
///                 text: label,
127
///                 style: const TextStyle(
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
///                   color: Colors.blueAccent,
///                   decoration: TextDecoration.underline,
///                 ),
///                 recognizer: TapGestureRecognizer()
///                   ..onTap = () {
///                   print('Label has been tapped.');
///                 },
///               ),
///             ),
///           ),
///           Switch(
///             value: value,
///             onChanged: (bool newValue) {
///               onChanged(newValue);
///             },
///           ),
///         ],
///       ),
///     );
///   }
/// }
/// ```
/// ```dart
/// bool _isSelected = false;
///
/// @override
/// Widget build(BuildContext context) {
155 156 157 158 159 160 161 162 163
///   return LinkedLabelSwitch(
///     label: 'Linked, tappable label text',
///     padding: const EdgeInsets.symmetric(horizontal: 20.0),
///     value: _isSelected,
///     onChanged: (bool newValue) {
///       setState(() {
///         _isSelected = newValue;
///       });
///     },
164 165 166 167 168 169 170 171 172 173 174 175
///   );
/// }
/// ```
/// {@end-tool}
///
/// ## SwitchListTile isn't exactly what I want
///
/// If the way SwitchListTile pads and positions its elements isn't quite what
/// you're looking for, you can create custom labeled switch widgets by
/// combining [Switch] with other widgets, such as [Text], [Padding] and
/// [InkWell].
///
176
/// {@tool dartpad --template=stateful_widget_scaffold_center}
177 178 179 180 181 182 183 184 185
///
/// ![Custom switch list tile sample](https://flutter.github.io/assets-for-api-docs/assets/material/switch_list_tile_custom.png)
///
/// Here is an example of a custom LabeledSwitch widget, but you can easily
/// make your own configurable widget.
///
/// ```dart preamble
/// class LabeledSwitch extends StatelessWidget {
///   const LabeledSwitch({
186
///     Key? key,
187 188 189 190
///     required this.label,
///     required this.padding,
///     required this.value,
///     required this.onChanged,
191
///   }) : super(key: key);
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
///
///   final String label;
///   final EdgeInsets padding;
///   final bool value;
///   final Function onChanged;
///
///   @override
///   Widget build(BuildContext context) {
///     return InkWell(
///       onTap: () {
///         onChanged(!value);
///       },
///       child: Padding(
///         padding: padding,
///         child: Row(
///           children: <Widget>[
///             Expanded(child: Text(label)),
///             Switch(
///               value: value,
///               onChanged: (bool newValue) {
///                 onChanged(newValue);
///               },
///             ),
///           ],
///         ),
///       ),
///     );
///   }
/// }
/// ```
/// ```dart
/// bool _isSelected = false;
///
/// @override
/// Widget build(BuildContext context) {
227 228 229 230 231 232 233 234 235
///   return LabeledSwitch(
///     label: 'This is the label text',
///     padding: const EdgeInsets.symmetric(horizontal: 20.0),
///     value: _isSelected,
///     onChanged: (bool newValue) {
///       setState(() {
///         _isSelected = newValue;
///       });
///     },
236 237 238 239 240
///   );
/// }
/// ```
/// {@end-tool}
///
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
/// See also:
///
///  * [ListTileTheme], which can be used to affect the style of list tiles,
///    including switch list tiles.
///  * [CheckboxListTile], a similar widget for checkboxes.
///  * [RadioListTile], a similar widget for radio buttons.
///  * [ListTile] and [Switch], the widgets from which this widget is made.
class SwitchListTile extends StatelessWidget {
  /// Creates a combination of a list tile and a switch.
  ///
  /// The switch tile 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 tile with a new [value] to update the visual
  /// appearance of the 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.
  const SwitchListTile({
262 263 264
    Key? key,
    required this.value,
    required this.onChanged,
265
    this.tileColor,
266
    this.activeColor,
267 268 269
    this.activeTrackColor,
    this.inactiveThumbColor,
    this.inactiveTrackColor,
270 271 272 273
    this.activeThumbImage,
    this.inactiveThumbImage,
    this.title,
    this.subtitle,
274
    this.isThreeLine = false,
275
    this.dense,
276
    this.contentPadding,
277
    this.secondary,
278
    this.selected = false,
279
    this.autofocus = false,
280
    this.controlAffinity = ListTileControlAffinity.platform,
281
    this.shape,
282
    this.selectedTileColor,
283 284 285 286 287
  }) : _switchListTileType = _SwitchListTileType.material,
       assert(value != null),
       assert(isThreeLine != null),
       assert(!isThreeLine || subtitle != null),
       assert(selected != null),
288
       assert(autofocus != null),
289 290
       super(key: key);

291 292 293
  /// Creates a Material [ListTile] with an adaptive [Switch], following
  /// Material design's
  /// [Cross-platform guidelines](https://material.io/design/platform-guidance/cross-platform-adaptation.html).
294
  ///
295 296 297 298
  /// This widget uses [Switch.adaptive] to change the graphics of the switch
  /// component based on the ambient [ThemeData.platform]. On iOS and macOS, a
  /// [CupertinoSwitch] will be used. On other platforms a Material design
  /// [Switch] will be used.
299 300 301
  ///
  /// If a [CupertinoSwitch] is created, the following parameters are
  /// ignored: [activeTrackColor], [inactiveThumbColor], [inactiveTrackColor],
302
  /// [activeThumbImage], [inactiveThumbImage].
303
  const SwitchListTile.adaptive({
304 305 306
    Key? key,
    required this.value,
    required this.onChanged,
307
    this.tileColor,
308 309 310 311 312 313 314 315 316 317
    this.activeColor,
    this.activeTrackColor,
    this.inactiveThumbColor,
    this.inactiveTrackColor,
    this.activeThumbImage,
    this.inactiveThumbImage,
    this.title,
    this.subtitle,
    this.isThreeLine = false,
    this.dense,
318
    this.contentPadding,
319 320
    this.secondary,
    this.selected = false,
321
    this.autofocus = false,
322
    this.controlAffinity = ListTileControlAffinity.platform,
323
    this.shape,
324
    this.selectedTileColor,
325 326
  }) : _switchListTileType = _SwitchListTileType.adaptive,
       assert(value != null),
327 328 329
       assert(isThreeLine != null),
       assert(!isThreeLine || subtitle != null),
       assert(selected != null),
330
       assert(autofocus != null),
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
       super(key: key);

  /// Whether this switch is checked.
  ///
  /// This property must not be null.
  final bool value;

  /// 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 tile with the
  /// new value.
  ///
  /// If null, the switch will be displayed as disabled.
  ///
  /// 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:
  ///
  /// ```dart
351
  /// SwitchListTile(
352
  ///   value: _isSelected,
353 354
  ///   onChanged: (bool newValue) {
  ///     setState(() {
355
  ///       _isSelected = newValue;
356 357
  ///     });
  ///   },
358
  ///   title: Text('Selection'),
359
  /// )
360
  /// ```
361
  final ValueChanged<bool>? onChanged;
362 363 364 365

  /// The color to use when this switch is on.
  ///
  /// Defaults to accent color of the current [Theme].
366
  final Color? activeColor;
367

368 369 370
  /// The color to use on the track when this switch is on.
  ///
  /// Defaults to [ThemeData.toggleableActiveColor] with the opacity set at 50%.
371 372
  ///
  /// Ignored if created with [SwitchListTile.adaptive].
373
  final Color? activeTrackColor;
374 375 376 377

  /// The color to use on the thumb when this switch is off.
  ///
  /// Defaults to the colors described in the Material design specification.
378 379
  ///
  /// Ignored if created with [SwitchListTile.adaptive].
380
  final Color? inactiveThumbColor;
381 382 383 384

  /// The color to use on the track when this switch is off.
  ///
  /// Defaults to the colors described in the Material design specification.
385 386
  ///
  /// Ignored if created with [SwitchListTile.adaptive].
387
  final Color? inactiveTrackColor;
388

389 390 391
  /// {@macro flutter.material.ListTile.tileColor}
  final Color? tileColor;

392
  /// An image to use on the thumb of this switch when the switch is on.
393
  final ImageProvider? activeThumbImage;
394 395

  /// An image to use on the thumb of this switch when the switch is off.
396 397
  ///
  /// Ignored if created with [SwitchListTile.adaptive].
398
  final ImageProvider? inactiveThumbImage;
399 400 401 402

  /// The primary content of the list tile.
  ///
  /// Typically a [Text] widget.
403
  final Widget? title;
404 405 406 407

  /// Additional content displayed below the title.
  ///
  /// Typically a [Text] widget.
408
  final Widget? subtitle;
409 410 411 412

  /// A widget to display on the opposite side of the tile from the switch.
  ///
  /// Typically an [Icon] widget.
413
  final Widget? secondary;
414 415 416 417 418 419 420 421 422 423

  /// Whether this list tile is intended to display three lines of text.
  ///
  /// If false, the list tile is treated as having one line if the subtitle is
  /// null and treated as having two lines if the subtitle is non-null.
  final bool isThreeLine;

  /// Whether this list tile is part of a vertically dense list.
  ///
  /// If this property is null then its value is based on [ListTileTheme.dense].
424
  final bool? dense;
425

426 427 428 429 430 431 432
  /// The tile's internal padding.
  ///
  /// Insets a [SwitchListTile]'s contents: its [title], [subtitle],
  /// [secondary], and [Switch] widgets.
  ///
  /// If null, [ListTile]'s default of `EdgeInsets.symmetric(horizontal: 16.0)`
  /// is used.
433
  final EdgeInsetsGeometry? contentPadding;
434

435 436 437 438 439 440 441 442 443
  /// Whether to render icons and text in the [activeColor].
  ///
  /// No effort is made to automatically coordinate the [selected] state and the
  /// [value] state. To have the list tile appear selected when the switch is
  /// on, pass the same value to both.
  ///
  /// Normally, this property is left to its default value, false.
  final bool selected;

444 445 446
  /// {@macro flutter.widgets.Focus.autofocus}
  final bool autofocus;

447 448 449
  /// If adaptive, creates the switch with [Switch.adaptive].
  final _SwitchListTileType _switchListTileType;

450 451 452 453 454
  /// Defines the position of control and [secondary], relative to text.
  ///
  /// By default, the value of `controlAffinity` is [ListTileControlAffinity.platform].
  final ListTileControlAffinity controlAffinity;

455
  /// {@macro flutter.material.ListTileTheme.shape}
456 457
  final ShapeBorder? shape;

458 459 460
  /// If non-null, defines the background color when [SwitchListTile.selected] is true.
  final Color? selectedTileColor;

461 462
  @override
  Widget build(BuildContext context) {
463
    final Widget control;
464 465 466 467 468 469 470 471 472 473 474 475
    switch (_switchListTileType) {
      case _SwitchListTileType.adaptive:
        control = Switch.adaptive(
          value: value,
          onChanged: onChanged,
          activeColor: activeColor,
          activeThumbImage: activeThumbImage,
          inactiveThumbImage: inactiveThumbImage,
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          activeTrackColor: activeTrackColor,
          inactiveTrackColor: inactiveTrackColor,
          inactiveThumbColor: inactiveThumbColor,
476
          autofocus: autofocus,
477 478 479 480 481 482 483 484 485 486 487 488 489 490
        );
        break;

      case _SwitchListTileType.material:
        control = Switch(
          value: value,
          onChanged: onChanged,
          activeColor: activeColor,
          activeThumbImage: activeThumbImage,
          inactiveThumbImage: inactiveThumbImage,
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          activeTrackColor: activeTrackColor,
          inactiveTrackColor: inactiveTrackColor,
          inactiveThumbColor: inactiveThumbColor,
491
          autofocus: autofocus,
492 493
        );
    }
494

495
    Widget? leading, trailing;
496 497 498 499 500 501 502 503 504 505 506 507
    switch (controlAffinity) {
      case ListTileControlAffinity.leading:
        leading = control;
        trailing = secondary;
        break;
      case ListTileControlAffinity.trailing:
      case ListTileControlAffinity.platform:
        leading = secondary;
        trailing = control;
        break;
    }

508
    return MergeSemantics(
509
      child: ListTileTheme.merge(
510
        selectedColor: activeColor ?? Theme.of(context).toggleableActiveColor,
511
        child: ListTile(
512
          leading: leading,
513 514
          title: title,
          subtitle: subtitle,
515
          trailing: trailing,
516 517
          isThreeLine: isThreeLine,
          dense: dense,
518
          contentPadding: contentPadding,
519
          enabled: onChanged != null,
520
          onTap: onChanged != null ? () { onChanged!(!value); } : null,
521
          selected: selected,
522
          selectedTileColor: selectedTileColor,
523
          autofocus: autofocus,
524
          shape: shape,
525
          tileColor: tileColor,
526 527 528 529 530
        ),
      ),
    );
  }
}