checkbox.dart 13.3 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:math' as math;
6

7 8
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
9

10
import 'constants.dart';
11
import 'debug.dart';
12
import 'theme.dart';
13
import 'theme_data.dart';
14
import 'toggleable.dart';
15

16
/// A material design checkbox.
17 18
///
/// The checkbox itself does not maintain any state. Instead, when the state of
19 20 21
/// 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 with a new [value] to update the visual appearance of
22 23
/// the checkbox.
///
24 25 26 27
/// The checkbox can optionally display three values - true, false, and null -
/// if [tristate] is true. When [value] is null a dash is displayed. By default
/// [tristate] is false and the checkbox's [value] must be true or false.
///
28 29 30
/// Requires one of its ancestors to be a [Material] widget.
///
/// See also:
31
///
32 33 34
///  * [CheckboxListTile], which combines this widget with a [ListTile] so that
///    you can give the checkbox a label.
///  * [Switch], a widget with semantics similar to [Checkbox].
35 36
///  * [Radio], for selecting among a set of explicit values.
///  * [Slider], for selecting a value in a range.
37 38
///  * <https://material.io/design/components/selection-controls.html#checkboxes>
///  * <https://material.io/design/components/lists.html#types>
39
class Checkbox extends StatefulWidget {
40
  /// Creates a material design checkbox.
41
  ///
42 43 44 45 46 47
  /// The checkbox 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 with a new [value] to update the visual appearance of
  /// the checkbox.
  ///
48 49
  /// The following arguments are required:
  ///
50
  /// * [value], which determines whether the checkbox is checked. The [value]
51
  ///   can only be null if [tristate] is true.
52 53
  /// * [onChanged], which is called when the value of the checkbox should
  ///   change. It can be set to null to disable the checkbox.
54 55
  ///
  /// The value of [tristate] must not be null.
56
  const Checkbox({
57
    Key key,
58
    @required this.value,
59
    this.tristate = false,
60
    @required this.onChanged,
61
    this.activeColor,
62
    this.checkColor,
63
    this.materialTapTargetSize,
64 65
  }) : assert(tristate != null),
       assert(tristate || value != null),
66
       super(key: key);
67

68
  /// Whether this checkbox is checked.
69 70
  ///
  /// This property must not be null.
71
  final bool value;
72

73
  /// Called when the value of the checkbox should change.
74 75 76 77 78
  ///
  /// The checkbox passes the new value to the callback but does not actually
  /// change state until the parent widget rebuilds the checkbox with the new
  /// value.
  ///
79 80 81 82 83 84
  /// If this callback is null, the checkbox will be displayed as disabled
  /// and will not respond to input gestures.
  ///
  /// When the checkbox is tapped, if [tristate] is false (the default) then
  /// the [onChanged] callback will be applied to `!value`. If [tristate] is
  /// true this callback cycle from false to true to null.
85
  ///
86
  /// The callback provided to [onChanged] should update the state of the parent
87 88 89 90
  /// [StatefulWidget] using the [State.setState] method, so that the parent
  /// gets rebuilt; for example:
  ///
  /// ```dart
91
  /// Checkbox(
92 93 94 95 96 97
  ///   value: _throwShotAway,
  ///   onChanged: (bool newValue) {
  ///     setState(() {
  ///       _throwShotAway = newValue;
  ///     });
  ///   },
98
  /// )
99
  /// ```
Hixie's avatar
Hixie committed
100
  final ValueChanged<bool> onChanged;
101

102 103
  /// The color to use when this checkbox is checked.
  ///
104
  /// Defaults to [ThemeData.toggleableActiveColor].
105 106
  final Color activeColor;

107 108 109 110 111
  /// The color to use for the check icon when this checkbox is checked
  ///
  /// Defaults to Color(0xFFFFFFFF)
  final Color checkColor;

112 113 114 115 116 117 118 119 120 121 122 123
  /// 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 is tapped its [onChanged] callback will be
  /// applied to true if the current value is null or false, false otherwise.
  /// Typically tri-state checkboxes are disabled (the onChanged callback is
  /// null) so they don't respond to taps.
  ///
  /// If tristate is false (the default), [value] must not be null.
  final bool tristate;

124 125 126 127 128 129
  /// Configures the minimum size of the tap target.
  ///
  /// Defaults to [ThemeData.materialTapTargetSize].
  ///
  /// See also:
  ///
130
  ///  * [MaterialTapTargetSize], for a description of how this affects tap targets.
131 132
  final MaterialTapTargetSize materialTapTargetSize;

133 134 135
  /// The width of a checkbox widget.
  static const double width = 18.0;

136
  @override
137
  _CheckboxState createState() => _CheckboxState();
138 139 140
}

class _CheckboxState extends State<Checkbox> with TickerProviderStateMixin {
141
  @override
142
  Widget build(BuildContext context) {
143
    assert(debugCheckHasMaterial(context));
144
    final ThemeData themeData = Theme.of(context);
145 146 147 148 149 150 151 152 153
    Size size;
    switch (widget.materialTapTargetSize ?? themeData.materialTapTargetSize) {
      case MaterialTapTargetSize.padded:
        size = const Size(2 * kRadialReactionRadius + 8.0, 2 * kRadialReactionRadius + 8.0);
        break;
      case MaterialTapTargetSize.shrinkWrap:
        size = const Size(2 * kRadialReactionRadius, 2 * kRadialReactionRadius);
        break;
    }
154 155
    final BoxConstraints additionalConstraints = BoxConstraints.tight(size);
    return _CheckboxRenderObjectWidget(
156
      value: widget.value,
157
      tristate: widget.tristate,
158
      activeColor: widget.activeColor ?? themeData.toggleableActiveColor,
159
      checkColor: widget.checkColor ?? const Color(0xFFFFFFFF),
160 161
      inactiveColor: widget.onChanged != null ? themeData.unselectedWidgetColor : themeData.disabledColor,
      onChanged: widget.onChanged,
162
      additionalConstraints: additionalConstraints,
163
      vsync: this,
164
    );
165 166 167
  }
}

168
class _CheckboxRenderObjectWidget extends LeafRenderObjectWidget {
169
  const _CheckboxRenderObjectWidget({
170
    Key key,
171
    @required this.value,
172
    @required this.tristate,
173
    @required this.activeColor,
174
    @required this.checkColor,
175 176 177
    @required this.inactiveColor,
    @required this.onChanged,
    @required this.vsync,
178
    @required this.additionalConstraints,
179 180
  }) : assert(tristate != null),
       assert(tristate || value != null),
181 182 183 184
       assert(activeColor != null),
       assert(inactiveColor != null),
       assert(vsync != null),
       super(key: key);
185 186

  final bool value;
187
  final bool tristate;
188
  final Color activeColor;
189
  final Color checkColor;
190
  final Color inactiveColor;
191
  final ValueChanged<bool> onChanged;
192
  final TickerProvider vsync;
193
  final BoxConstraints additionalConstraints;
194

195
  @override
196
  _RenderCheckbox createRenderObject(BuildContext context) => _RenderCheckbox(
197
    value: value,
198
    tristate: tristate,
199
    activeColor: activeColor,
200
    checkColor: checkColor,
201
    inactiveColor: inactiveColor,
202 203
    onChanged: onChanged,
    vsync: vsync,
204
    additionalConstraints: additionalConstraints,
205
  );
206

207
  @override
208
  void updateRenderObject(BuildContext context, _RenderCheckbox renderObject) {
209 210
    renderObject
      ..value = value
211
      ..tristate = tristate
212
      ..activeColor = activeColor
213
      ..checkColor = checkColor
214
      ..inactiveColor = inactiveColor
215
      ..onChanged = onChanged
216
      ..additionalConstraints = additionalConstraints
217
      ..vsync = vsync;
218 219 220
  }
}

221
const double _kEdgeSize = Checkbox.width;
222
const Radius _kEdgeRadius = Radius.circular(1.0);
223 224
const double _kStrokeWidth = 2.0;

225
class _RenderCheckbox extends RenderToggleable {
226 227
  _RenderCheckbox({
    bool value,
228
    bool tristate,
229
    Color activeColor,
230
    this.checkColor,
231
    Color inactiveColor,
232
    BoxConstraints additionalConstraints,
233 234
    ValueChanged<bool> onChanged,
    @required TickerProvider vsync,
235 236 237 238 239 240 241 242 243 244
  }) : _oldValue = value,
       super(
         value: value,
         tristate: tristate,
         activeColor: activeColor,
         inactiveColor: inactiveColor,
         onChanged: onChanged,
         additionalConstraints: additionalConstraints,
         vsync: vsync,
       );
245 246

  bool _oldValue;
247
  Color checkColor;
248

249
  @override
250 251 252 253 254 255
  set value(bool newValue) {
    if (newValue == value)
      return;
    _oldValue = value;
    super.value = newValue;
  }
256

257 258 259 260 261 262
  @override
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
    config.isChecked = value == true;
  }

263 264 265 266 267 268 269
  // The square outer bounds of the checkbox at t, with the specified origin.
  // At t == 0.0, the outer rect's size is _kEdgeSize (Checkbox.width)
  // At t == 0.5, .. is _kEdgeSize - _kStrokeWidth
  // At t == 1.0, .. is _kEdgeSize
  RRect _outerRectAt(Offset origin, double t) {
    final double inset = 1.0 - (t - 0.5).abs() * 2.0;
    final double size = _kEdgeSize - inset * _kStrokeWidth;
270 271
    final Rect rect = Rect.fromLTWH(origin.dx + inset, origin.dy + inset, size, size);
    return RRect.fromRectAndRadius(rect, _kEdgeRadius);
272
  }
273

274 275 276 277 278 279 280 281 282 283 284 285
  // The checkbox's border color if value == false, or its fill color when
  // value == true or null.
  Color _colorAt(double t) {
    // As t goes from 0.0 to 0.25, animate from the inactiveColor to activeColor.
    return onChanged == null
      ? inactiveColor
      : (t >= 0.25 ? activeColor : Color.lerp(inactiveColor, activeColor, t * 4.0));
  }

  // White stroke used to paint the check and dash.
  void _initStrokePaint(Paint paint) {
    paint
286
      ..color = checkColor
287 288 289 290 291 292 293 294 295 296 297 298 299 300
      ..style = PaintingStyle.stroke
      ..strokeWidth = _kStrokeWidth;
  }

  void _drawBorder(Canvas canvas, RRect outer, double t, Paint paint) {
    assert(t >= 0.0 && t <= 0.5);
    final double size = outer.width;
    // As t goes from 0.0 to 1.0, gradually fill the outer RRect.
    final RRect inner = outer.deflate(math.min(size / 2.0, _kStrokeWidth + size * t));
    canvas.drawDRRect(outer, inner, paint);
  }

  void _drawCheck(Canvas canvas, Offset origin, double t, Paint paint) {
    assert(t >= 0.0 && t <= 1.0);
301 302
    // As t goes from 0.0 to 1.0, animate the two check mark strokes from the
    // short side to the long side.
303
    final Path path = Path();
304 305 306
    const Offset start = Offset(_kEdgeSize * 0.15, _kEdgeSize * 0.45);
    const Offset mid = Offset(_kEdgeSize * 0.4, _kEdgeSize * 0.7);
    const Offset end = Offset(_kEdgeSize * 0.85, _kEdgeSize * 0.25);
307 308 309 310 311 312 313 314 315 316 317 318
    if (t < 0.5) {
      final double strokeT = t * 2.0;
      final Offset drawMid = Offset.lerp(start, mid, strokeT);
      path.moveTo(origin.dx + start.dx, origin.dy + start.dy);
      path.lineTo(origin.dx + drawMid.dx, origin.dy + drawMid.dy);
    } else {
      final double strokeT = (t - 0.5) * 2.0;
      final Offset drawEnd = Offset.lerp(mid, end, strokeT);
      path.moveTo(origin.dx + start.dx, origin.dy + start.dy);
      path.lineTo(origin.dx + mid.dx, origin.dy + mid.dy);
      path.lineTo(origin.dx + drawEnd.dx, origin.dy + drawEnd.dy);
    }
319 320
    canvas.drawPath(path, paint);
  }
321

322 323 324 325
  void _drawDash(Canvas canvas, Offset origin, double t, Paint paint) {
    assert(t >= 0.0 && t <= 1.0);
    // As t goes from 0.0 to 1.0, animate the horizontal line from the
    // mid point outwards.
326 327 328
    const Offset start = Offset(_kEdgeSize * 0.2, _kEdgeSize * 0.5);
    const Offset mid = Offset(_kEdgeSize * 0.5, _kEdgeSize * 0.5);
    const Offset end = Offset(_kEdgeSize * 0.8, _kEdgeSize * 0.5);
329 330 331 332 333 334 335 336
    final Offset drawStart = Offset.lerp(start, mid, 1.0 - t);
    final Offset drawEnd = Offset.lerp(mid, end, t);
    canvas.drawLine(origin + drawStart, origin + drawEnd, paint);
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    final Canvas canvas = context.canvas;
337
    paintRadialReaction(canvas, offset, size.center(Offset.zero));
338

339 340 341 342 343
    final Offset origin = offset + (size / 2.0 - const Size.square(_kEdgeSize) / 2.0);
    final AnimationStatus status = position.status;
    final double tNormalized = status == AnimationStatus.forward || status == AnimationStatus.completed
      ? position.value
      : 1.0 - position.value;
344

345 346 347 348
    // Four cases: false to null, false to true, null to false, true to false
    if (_oldValue == false || value == false) {
      final double t = value == false ? 1.0 - tNormalized : tNormalized;
      final RRect outer = _outerRectAt(origin, t);
349
      final Paint paint = Paint()..color = _colorAt(t);
350

351 352 353 354
      if (t <= 0.5) {
        _drawBorder(canvas, outer, t, paint);
      } else {
        canvas.drawRRect(outer, paint);
355

356 357
        _initStrokePaint(paint);
        final double tShrink = (t - 0.5) * 2.0;
358
        if (_oldValue == null || value == null)
359 360 361 362 363 364
          _drawDash(canvas, origin, tShrink, paint);
        else
          _drawCheck(canvas, origin, tShrink, paint);
      }
    } else { // Two cases: null to true, true to null
      final RRect outer = _outerRectAt(origin, 1.0);
365
      final Paint paint = Paint() ..color = _colorAt(1.0);
366
      canvas.drawRRect(outer, paint);
367

368 369 370 371 372 373 374 375 376 377 378 379 380 381
      _initStrokePaint(paint);
      if (tNormalized <= 0.5) {
        final double tShrink = 1.0 - tNormalized * 2.0;
        if (_oldValue == true)
          _drawCheck(canvas, origin, tShrink, paint);
        else
          _drawDash(canvas, origin, tShrink, paint);
      } else {
        final double tExpand = (tNormalized - 0.5) * 2.0;
        if (value == true)
          _drawCheck(canvas, origin, tExpand, paint);
        else
          _drawDash(canvas, origin, tExpand, paint);
      }
382 383 384
    }
  }
}