checkbox_list_tile.dart 11.9 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 'checkbox.dart';
import 'list_tile.dart';
import 'theme.dart';
10
import 'theme_data.dart';
11

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

15 16 17 18 19
/// A [ListTile] with a [Checkbox]. In other words, a checkbox with a label.
///
/// The entire list tile is interactive: tapping anywhere in the tile toggles
/// the checkbox.
///
20 21
/// {@youtube 560 315 https://www.youtube.com/watch?v=RkSqPAn9szs}
///
22
/// The [value], [onChanged], [activeColor] and [checkColor] properties of this widget are
23 24
/// identical to the similarly-named properties on the [Checkbox] widget.
///
25
/// The [title], [subtitle], [isThreeLine], [dense], and [contentPadding] properties are like
26 27 28
/// those of the same name on [ListTile].
///
/// The [selected] property on this widget is similar to the [ListTile.selected]
29 30 31 32
/// 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] state; to have the list tile
33
/// appear selected when the checkbox is checked, pass the same value to both.
34 35 36 37 38 39
///
/// The checkbox is shown on the right by default in left-to-right languages
/// (i.e. the trailing edge). This can be changed using [controlAffinity]. The
/// [secondary] widget is placed on the opposite side. This maps to the
/// [ListTile.leading] and [ListTile.trailing] properties of [ListTile].
///
40 41 42
/// To show the [CheckboxListTile] as disabled, pass null as the [onChanged]
/// callback.
///
43
/// {@tool dartpad}
44
/// ![CheckboxListTile sample](https://flutter.github.io/assets-for-api-docs/assets/material/checkbox_list_tile.png)
45 46 47 48
///
/// This widget shows a checkbox that, when checked, slows down all animations
/// (including the animation of the checkbox itself getting checked!).
///
49 50 51
/// This sample requires that you also import 'package:flutter/scheduler.dart',
/// so that you can reference [timeDilation].
///
52
/// ** See code in examples/api/lib/material/checkbox_list_tile/checkbox_list_tile.0.dart **
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
/// {@end-tool}
///
/// ## Semantics in CheckboxListTile
///
/// Since the entirety of the CheckboxListTile is interactive, it should represent
/// itself as a single interactive entity.
///
/// To do so, a CheckboxListTile 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, CheckboxListTile 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
/// CheckboxListTile. [RichText] has an embedded gesture recognizer that
/// requires its own [Semantics] node, which directly conflicts with
/// CheckboxListTile'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.
///
72
/// {@tool dartpad}
73 74 75 76 77 78
/// ![Checkbox list tile semantics sample](https://flutter.github.io/assets-for-api-docs/assets/material/checkbox_list_tile_semantics.png)
///
/// Here is an example of a custom labeled checkbox widget, called
/// LinkedLabelCheckbox, that includes an interactive [RichText] widget that
/// handles tap gestures.
///
79
/// ** See code in examples/api/lib/material/checkbox_list_tile/checkbox_list_tile.1.dart **
80 81 82 83 84 85 86 87 88
/// {@end-tool}
///
/// ## CheckboxListTile isn't exactly what I want
///
/// If the way CheckboxListTile pads and positions its elements isn't quite
/// what you're looking for, you can create custom labeled checkbox widgets by
/// combining [Checkbox] with other widgets, such as [Text], [Padding] and
/// [InkWell].
///
89
/// {@tool dartpad}
90 91 92 93 94
/// ![Custom checkbox list tile sample](https://flutter.github.io/assets-for-api-docs/assets/material/checkbox_list_tile_custom.png)
///
/// Here is an example of a custom LabeledCheckbox widget, but you can easily
/// make your own configurable widget.
///
95
/// ** See code in examples/api/lib/material/checkbox_list_tile/checkbox_list_tile.2.dart **
96
/// {@end-tool}
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
///
/// See also:
///
///  * [ListTileTheme], which can be used to affect the style of list tiles,
///    including checkbox list tiles.
///  * [RadioListTile], a similar widget for radio buttons.
///  * [SwitchListTile], a similar widget for switches.
///  * [ListTile] and [Checkbox], the widgets from which this widget is made.
class CheckboxListTile extends StatelessWidget {
  /// Creates a combination of a list tile and a checkbox.
  ///
  /// The checkbox tile itself does not maintain any state. Instead, when the
  /// state of the checkbox changes, the widget calls the [onChanged] callback.
  /// Most widgets that use a checkbox will listen for the [onChanged] callback
  /// and rebuild the checkbox tile with a new [value] to update the visual
  /// appearance of the checkbox.
  ///
  /// The following arguments are required:
  ///
116 117
  /// * [value], which determines whether the checkbox is checked. The [value]
  ///   can only be null if [tristate] is true.
118 119
  /// * [onChanged], which is called when the value of the checkbox should
  ///   change. It can be set to null to disable the checkbox.
120 121
  ///
  /// The value of [tristate] must not be null.
122
  const CheckboxListTile({
123 124 125
    Key? key,
    required this.value,
    required this.onChanged,
126
    this.activeColor,
127
    this.checkColor,
128
    this.tileColor,
129 130
    this.title,
    this.subtitle,
131
    this.isThreeLine = false,
132 133
    this.dense,
    this.secondary,
134 135
    this.selected = false,
    this.controlAffinity = ListTileControlAffinity.platform,
136
    this.autofocus = false,
137
    this.contentPadding,
138
    this.tristate = false,
139
    this.shape,
140
    this.selectedTileColor,
141 142 143
    this.visualDensity,
    this.focusNode,
    this.enableFeedback,
144 145
  }) : assert(tristate != null),
       assert(tristate || value != null),
146 147 148 149
       assert(isThreeLine != null),
       assert(!isThreeLine || subtitle != null),
       assert(selected != null),
       assert(controlAffinity != null),
150
       assert(autofocus != null),
151 152 153
       super(key: key);

  /// Whether this checkbox is checked.
154
  final bool? value;
155 156 157 158 159 160 161 162 163 164 165 166 167 168

  /// Called when the value of the checkbox should change.
  ///
  /// The checkbox passes the new value to the callback but does not actually
  /// change state until the parent widget rebuilds the checkbox tile with the
  /// new value.
  ///
  /// If null, the checkbox 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
169
  /// CheckboxListTile(
170 171 172 173 174 175
  ///   value: _throwShotAway,
  ///   onChanged: (bool newValue) {
  ///     setState(() {
  ///       _throwShotAway = newValue;
  ///     });
  ///   },
176
  ///   title: Text('Throw away your shot'),
177
  /// )
178
  /// ```
179
  final ValueChanged<bool?>? onChanged;
180 181 182

  /// The color to use when this checkbox is checked.
  ///
183
  /// Defaults to accent color of the current [Theme].
184
  final Color? activeColor;
185

186 187 188
  /// The color to use for the check icon when this checkbox is checked.
  ///
  /// Defaults to Color(0xFFFFFFFF).
189
  final Color? checkColor;
190

191 192 193
  /// {@macro flutter.material.ListTile.tileColor}
  final Color? tileColor;

194 195 196
  /// The primary content of the list tile.
  ///
  /// Typically a [Text] widget.
197
  final Widget? title;
198 199 200 201

  /// Additional content displayed below the title.
  ///
  /// Typically a [Text] widget.
202
  final Widget? subtitle;
203 204 205 206

  /// A widget to display on the opposite side of the tile from the checkbox.
  ///
  /// Typically an [Icon] widget.
207
  final Widget? secondary;
208 209 210 211 212 213 214 215 216 217

  /// 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].
218
  final bool? dense;
219 220 221 222 223 224 225 226 227 228 229 230 231

  /// 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 checkbox is
  /// checked, pass the same value to both.
  ///
  /// Normally, this property is left to its default value, false.
  final bool selected;

  /// Where to place the control relative to the text.
  final ListTileControlAffinity controlAffinity;

232 233 234
  /// {@macro flutter.widgets.Focus.autofocus}
  final bool autofocus;

235 236 237 238 239 240
  /// Defines insets surrounding the tile's contents.
  ///
  /// This value will surround the [Checkbox], [title], [subtitle], and [secondary]
  /// widgets in [CheckboxListTile].
  ///
  /// When the value is null, the `contentPadding` is `EdgeInsets.symmetric(horizontal: 16.0)`.
241
  final EdgeInsetsGeometry? contentPadding;
242

243 244 245 246 247 248 249 250 251 252 253 254
  /// If true the checkbox's [value] can be true, false, or null.
  ///
  /// Checkbox displays a dash when its value is null.
  ///
  /// When a tri-state checkbox ([tristate] is true) is tapped, its [onChanged]
  /// callback will be applied to true if the current value is false, to null if
  /// value is true, and to false if value is null (i.e. it cycles through false
  /// => true => null => false when tapped).
  ///
  /// If tristate is false (the default), [value] must not be null.
  final bool tristate;

255
  /// {@macro flutter.material.ListTileTheme.shape}
256 257
  final ShapeBorder? shape;

258 259 260
  /// If non-null, defines the background color when [CheckboxListTile.selected] is true.
  final Color? selectedTileColor;

261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
  /// Defines how compact the list tile's layout will be.
  ///
  /// {@macro flutter.material.themedata.visualDensity}
  final VisualDensity? visualDensity;

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

  /// {@macro flutter.material.ListTile.enableFeedback}
  ///
  /// See also:
  ///
  ///  * [Feedback] for providing platform-specific feedback to certain actions.
  final bool? enableFeedback;

276 277 278 279
  void _handleValueChange() {
    assert(onChanged != null);
    switch (value) {
      case false:
280
        onChanged!(true);
281 282
        break;
      case true:
283
        onChanged!(tristate ? null : false);
284
        break;
285 286
      case null:
        onChanged!(false);
287 288 289 290
        break;
    }
  }

291 292
  @override
  Widget build(BuildContext context) {
293
    final Widget control = Checkbox(
294 295 296
      value: value,
      onChanged: onChanged,
      activeColor: activeColor,
297
      checkColor: checkColor,
298
      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
299
      autofocus: autofocus,
300
      tristate: tristate,
301
    );
302
    Widget? leading, trailing;
303 304 305 306 307 308 309 310 311 312 313
    switch (controlAffinity) {
      case ListTileControlAffinity.leading:
        leading = control;
        trailing = secondary;
        break;
      case ListTileControlAffinity.trailing:
      case ListTileControlAffinity.platform:
        leading = secondary;
        trailing = control;
        break;
    }
314
    return MergeSemantics(
315
      child: ListTileTheme.merge(
316
        selectedColor: activeColor ?? Theme.of(context).toggleableActiveColor,
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
        child: ListTile(
          leading: leading,
          title: title,
          subtitle: subtitle,
          trailing: trailing,
          isThreeLine: isThreeLine,
          dense: dense,
          enabled: onChanged != null,
          onTap: onChanged != null ? _handleValueChange : null,
          selected: selected,
          autofocus: autofocus,
          contentPadding: contentPadding,
          shape: shape,
          selectedTileColor: selectedTileColor,
          tileColor: tileColor,
332 333 334
          visualDensity: visualDensity,
          focusNode: focusNode,
          enableFeedback: enableFeedback,
335
        ),
336 337 338 339
      ),
    );
  }
}