checkbox.dart 16.7 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
import 'dart:math' as math;
6

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

12
import 'constants.dart';
13
import 'debug.dart';
14
import 'theme.dart';
15
import 'theme_data.dart';
16
import 'toggleable.dart';
17

18
/// A material design checkbox.
19 20
///
/// The checkbox itself does not maintain any state. Instead, when the state of
21 22 23
/// 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
24 25
/// the checkbox.
///
26 27 28 29
/// 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.
///
30 31 32
/// Requires one of its ancestors to be a [Material] widget.
///
/// See also:
33
///
34 35 36
///  * [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].
37 38
///  * [Radio], for selecting among a set of explicit values.
///  * [Slider], for selecting a value in a range.
39 40
///  * <https://material.io/design/components/selection-controls.html#checkboxes>
///  * <https://material.io/design/components/lists.html#types>
41
class Checkbox extends StatefulWidget {
42
  /// Creates a material design checkbox.
43
  ///
44 45 46 47 48 49
  /// 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.
  ///
50 51
  /// The following arguments are required:
  ///
52
  /// * [value], which determines whether the checkbox is checked. The [value]
53
  ///   can only be null if [tristate] is true.
54 55
  /// * [onChanged], which is called when the value of the checkbox should
  ///   change. It can be set to null to disable the checkbox.
56
  ///
57
  /// The values of [tristate] and [autofocus] must not be null.
58
  const Checkbox({
59
    Key key,
60
    @required this.value,
61
    this.tristate = false,
62
    @required this.onChanged,
63
    this.activeColor,
64
    this.checkColor,
65 66
    this.focusColor,
    this.hoverColor,
67
    this.materialTapTargetSize,
68
    this.visualDensity,
69 70
    this.focusNode,
    this.autofocus = false,
71 72
  }) : assert(tristate != null),
       assert(tristate || value != null),
73
       assert(autofocus != null),
74
       super(key: key);
75

76
  /// Whether this checkbox is checked.
77 78
  ///
  /// This property must not be null.
79
  final bool value;
80

81
  /// Called when the value of the checkbox should change.
82 83 84 85 86
  ///
  /// 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.
  ///
87 88 89 90 91 92
  /// 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.
93
  ///
94
  /// The callback provided to [onChanged] should update the state of the parent
95 96 97 98
  /// [StatefulWidget] using the [State.setState] method, so that the parent
  /// gets rebuilt; for example:
  ///
  /// ```dart
99
  /// Checkbox(
100 101 102 103 104 105
  ///   value: _throwShotAway,
  ///   onChanged: (bool newValue) {
  ///     setState(() {
  ///       _throwShotAway = newValue;
  ///     });
  ///   },
106
  /// )
107
  /// ```
Hixie's avatar
Hixie committed
108
  final ValueChanged<bool> onChanged;
109

110 111
  /// The color to use when this checkbox is checked.
  ///
112
  /// Defaults to [ThemeData.toggleableActiveColor].
113 114
  final Color activeColor;

115
  /// The color to use for the check icon when this checkbox is checked.
116 117 118 119
  ///
  /// Defaults to Color(0xFFFFFFFF)
  final Color checkColor;

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.
  ///
124 125 126 127
  /// 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).
128 129 130 131
  ///
  /// If tristate is false (the default), [value] must not be null.
  final bool tristate;

132 133 134 135 136 137
  /// Configures the minimum size of the tap target.
  ///
  /// Defaults to [ThemeData.materialTapTargetSize].
  ///
  /// See also:
  ///
138
  ///  * [MaterialTapTargetSize], for a description of how this affects tap targets.
139 140
  final MaterialTapTargetSize materialTapTargetSize;

141 142 143 144 145 146 147 148 149 150
  /// Defines how compact the checkbox's layout will be.
  ///
  /// {@macro flutter.material.themedata.visualDensity}
  ///
  /// See also:
  ///
  ///  * [ThemeData.visualDensity], which specifies the [density] for all widgets
  ///    within a [Theme].
  final VisualDensity visualDensity;

151 152 153 154 155 156 157 158 159 160 161 162
  /// The color for the checkbox's [Material] when it has the input focus.
  final Color focusColor;

  /// The color for the checkbox's [Material] when a pointer is hovering over it.
  final Color hoverColor;

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

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

163 164 165
  /// The width of a checkbox widget.
  static const double width = 18.0;

166
  @override
167
  _CheckboxState createState() => _CheckboxState();
168 169 170
}

class _CheckboxState extends State<Checkbox> with TickerProviderStateMixin {
171
  bool get enabled => widget.onChanged != null;
172
  Map<Type, Action<Intent>> _actionMap;
173 174 175 176

  @override
  void initState() {
    super.initState();
177 178
    _actionMap = <Type, Action<Intent>>{
      ActivateIntent: CallbackAction<ActivateIntent>(onInvoke: _actionHandler),
179 180 181
    };
  }

182
  void _actionHandler(ActivateIntent intent) {
183 184 185 186 187 188 189 190 191 192 193 194 195
    if (widget.onChanged != null) {
      switch (widget.value) {
        case false:
          widget.onChanged(true);
          break;
        case true:
          widget.onChanged(widget.tristate ? null : false);
          break;
        default: // case null:
          widget.onChanged(false);
          break;
      }
    }
196
    final RenderObject renderObject = context.findRenderObject();
197 198 199
    renderObject.sendSemanticsEvent(const TapSemanticEvent());
  }

200 201 202 203
  bool _focused = false;
  void _handleFocusHighlightChanged(bool focused) {
    if (focused != _focused) {
      setState(() { _focused = focused; });
204 205 206
    }
  }

207 208 209 210
  bool _hovering = false;
  void _handleHoverChanged(bool hovering) {
    if (hovering != _hovering) {
      setState(() { _hovering = hovering; });
211 212 213
    }
  }

214
  @override
215
  Widget build(BuildContext context) {
216
    assert(debugCheckHasMaterial(context));
217
    final ThemeData themeData = Theme.of(context);
218 219 220 221 222 223 224 225 226
    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;
    }
227
    size += (widget.visualDensity ?? themeData.visualDensity).baseSizeAdjustment;
228
    final BoxConstraints additionalConstraints = BoxConstraints.tight(size);
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    return FocusableActionDetector(
      actions: _actionMap,
      focusNode: widget.focusNode,
      autofocus: widget.autofocus,
      enabled: enabled,
      onShowFocusHighlight: _handleFocusHighlightChanged,
      onShowHoverHighlight: _handleHoverChanged,
      child: Builder(
        builder: (BuildContext context) {
          return _CheckboxRenderObjectWidget(
            value: widget.value,
            tristate: widget.tristate,
            activeColor: widget.activeColor ?? themeData.toggleableActiveColor,
            checkColor: widget.checkColor ?? const Color(0xFFFFFFFF),
            inactiveColor: enabled ? themeData.unselectedWidgetColor : themeData.disabledColor,
            focusColor: widget.focusColor ?? themeData.focusColor,
            hoverColor: widget.hoverColor ?? themeData.hoverColor,
            onChanged: widget.onChanged,
            additionalConstraints: additionalConstraints,
            vsync: this,
            hasFocus: _focused,
            hovering: _hovering,
          );
        },
253
      ),
254
    );
255 256 257
  }
}

258
class _CheckboxRenderObjectWidget extends LeafRenderObjectWidget {
259
  const _CheckboxRenderObjectWidget({
260
    Key key,
261
    @required this.value,
262
    @required this.tristate,
263
    @required this.activeColor,
264
    @required this.checkColor,
265
    @required this.inactiveColor,
266 267
    @required this.focusColor,
    @required this.hoverColor,
268 269
    @required this.onChanged,
    @required this.vsync,
270
    @required this.additionalConstraints,
271 272
    @required this.hasFocus,
    @required this.hovering,
273 274
  }) : assert(tristate != null),
       assert(tristate || value != null),
275 276 277 278
       assert(activeColor != null),
       assert(inactiveColor != null),
       assert(vsync != null),
       super(key: key);
279 280

  final bool value;
281
  final bool tristate;
282 283
  final bool hasFocus;
  final bool hovering;
284
  final Color activeColor;
285
  final Color checkColor;
286
  final Color inactiveColor;
287 288
  final Color focusColor;
  final Color hoverColor;
289
  final ValueChanged<bool> onChanged;
290
  final TickerProvider vsync;
291
  final BoxConstraints additionalConstraints;
292

293
  @override
294
  _RenderCheckbox createRenderObject(BuildContext context) => _RenderCheckbox(
295
    value: value,
296
    tristate: tristate,
297
    activeColor: activeColor,
298
    checkColor: checkColor,
299
    inactiveColor: inactiveColor,
300 301
    focusColor: focusColor,
    hoverColor: hoverColor,
302 303
    onChanged: onChanged,
    vsync: vsync,
304
    additionalConstraints: additionalConstraints,
305 306
    hasFocus: hasFocus,
    hovering: hovering,
307
  );
308

309
  @override
310
  void updateRenderObject(BuildContext context, _RenderCheckbox renderObject) {
311 312
    renderObject
      ..value = value
313
      ..tristate = tristate
314
      ..activeColor = activeColor
315
      ..checkColor = checkColor
316
      ..inactiveColor = inactiveColor
317 318
      ..focusColor = focusColor
      ..hoverColor = hoverColor
319
      ..onChanged = onChanged
320
      ..additionalConstraints = additionalConstraints
321 322 323
      ..vsync = vsync
      ..hasFocus = hasFocus
      ..hovering = hovering;
324 325 326
  }
}

327
const double _kEdgeSize = Checkbox.width;
328
const Radius _kEdgeRadius = Radius.circular(1.0);
329 330
const double _kStrokeWidth = 2.0;

331
class _RenderCheckbox extends RenderToggleable {
332 333
  _RenderCheckbox({
    bool value,
334
    bool tristate,
335
    Color activeColor,
336
    this.checkColor,
337
    Color inactiveColor,
338 339
    Color focusColor,
    Color hoverColor,
340
    BoxConstraints additionalConstraints,
341
    ValueChanged<bool> onChanged,
342 343
    bool hasFocus,
    bool hovering,
344
    @required TickerProvider vsync,
345 346 347 348 349 350
  }) : _oldValue = value,
       super(
         value: value,
         tristate: tristate,
         activeColor: activeColor,
         inactiveColor: inactiveColor,
351 352
         focusColor: focusColor,
         hoverColor: hoverColor,
353 354 355
         onChanged: onChanged,
         additionalConstraints: additionalConstraints,
         vsync: vsync,
356 357
         hasFocus: hasFocus,
         hovering: hovering,
358
       );
359 360

  bool _oldValue;
361
  Color checkColor;
362

363
  @override
364 365 366 367 368 369
  set value(bool newValue) {
    if (newValue == value)
      return;
    _oldValue = value;
    super.value = newValue;
  }
370

371 372 373 374 375 376
  @override
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
    config.isChecked = value == true;
  }

377 378 379 380 381 382 383
  // 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;
384 385
    final Rect rect = Rect.fromLTWH(origin.dx + inset, origin.dy + inset, size, size);
    return RRect.fromRectAndRadius(rect, _kEdgeRadius);
386
  }
387

388 389 390 391 392 393 394 395 396 397
  // 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.
398 399
  Paint _createStrokePaint() {
    return Paint()
400
      ..color = checkColor
401 402 403 404 405 406 407 408 409 410 411 412 413 414
      ..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);
415 416
    // As t goes from 0.0 to 1.0, animate the two check mark strokes from the
    // short side to the long side.
417
    final Path path = Path();
418 419 420
    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);
421 422 423 424 425 426 427 428 429 430 431 432
    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);
    }
433 434
    canvas.drawPath(path, paint);
  }
435

436 437 438 439
  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.
440 441 442
    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);
443 444 445 446 447 448 449 450
    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;
451
    paintRadialReaction(canvas, offset, size.center(Offset.zero));
452

453
    final Paint strokePaint = _createStrokePaint();
454
    final Offset origin = offset + (size / 2.0 - const Size.square(_kEdgeSize) / 2.0 as Offset);
455 456 457 458
    final AnimationStatus status = position.status;
    final double tNormalized = status == AnimationStatus.forward || status == AnimationStatus.completed
      ? position.value
      : 1.0 - position.value;
459

460 461 462 463
    // 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);
464
      final Paint paint = Paint()..color = _colorAt(t);
465

466 467 468 469
      if (t <= 0.5) {
        _drawBorder(canvas, outer, t, paint);
      } else {
        canvas.drawRRect(outer, paint);
470

471
        final double tShrink = (t - 0.5) * 2.0;
472
        if (_oldValue == null || value == null)
473
          _drawDash(canvas, origin, tShrink, strokePaint);
474
        else
475
          _drawCheck(canvas, origin, tShrink, strokePaint);
476 477 478
      }
    } else { // Two cases: null to true, true to null
      final RRect outer = _outerRectAt(origin, 1.0);
479
      final Paint paint = Paint() ..color = _colorAt(1.0);
480
      canvas.drawRRect(outer, paint);
481

482 483 484
      if (tNormalized <= 0.5) {
        final double tShrink = 1.0 - tNormalized * 2.0;
        if (_oldValue == true)
485
          _drawCheck(canvas, origin, tShrink, strokePaint);
486
        else
487
          _drawDash(canvas, origin, tShrink, strokePaint);
488 489 490
      } else {
        final double tExpand = (tNormalized - 0.5) * 2.0;
        if (value == true)
491
          _drawCheck(canvas, origin, tExpand, strokePaint);
492
        else
493
          _drawDash(canvas, origin, tExpand, strokePaint);
494
      }
495 496 497
    }
  }
}