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

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

import 'colors.dart';
13
import 'constants.dart';
14
import 'debug.dart';
15
import 'theme.dart';
16
import 'typography.dart';
17

18 19
/// A material design slider.
///
20 21 22 23 24 25 26 27
/// Used to select from a range of values.
///
/// A slider can be used to select from either a continuous or a discrete set of
/// values. The default is use a continuous range of values from [min] to [max].
/// To use discrete values, use a non-null value for [divisions], which
/// indicates the number of discrete intervals. For example, if [min] is 0.0 and
/// [max] is 50.0 and [divisions] is 5, then the slider can take on the values
/// discrete values 0.0, 10.0, 20.0, 30.0, 40.0, and 50.0.
28 29 30 31 32 33 34 35 36
///
/// The slider itself does not maintain any state. Instead, when the state of
/// the slider changes, the widget calls the [onChanged] callback. Most widgets
/// that use a slider will listen for the [onChanged] callback and rebuild the
/// slider with a new [value] to update the visual appearance of the slider.
///
/// Requires one of its ancestors to be a [Material] widget.
///
/// See also:
37
///
38 39 40
///  * [CheckBox]
///  * [Radio]
///  * [Switch]
41
///  * <https://material.google.com/components/sliders.html>
42
class Slider extends StatefulWidget {
43 44 45 46 47 48 49 50 51
  /// Creates a material design slider.
  ///
  /// The slider itself does not maintain any state. Instead, when the state of
  /// the slider changes, the widget calls the [onChanged] callback. Most widgets
  /// that use a slider will listen for the [onChanged] callback and rebuild the
  /// slider with a new [value] to update the visual appearance of the slider.
  ///
  /// * [value] determines currently selected value for this slider.
  /// * [onChanged] is called when the user selects a new value for the slider.
Hixie's avatar
Hixie committed
52 53
  Slider({
    Key key,
54 55
    @required this.value,
    @required this.onChanged,
Hixie's avatar
Hixie committed
56 57
    this.min: 0.0,
    this.max: 1.0,
58 59
    this.divisions,
    this.label,
60
    this.activeColor
Hixie's avatar
Hixie committed
61 62 63 64 65
  }) : super(key: key) {
    assert(value != null);
    assert(min != null);
    assert(max != null);
    assert(value >= min && value <= max);
66
    assert(divisions == null || divisions > 0);
Hixie's avatar
Hixie committed
67
  }
68

69 70 71
  /// The currently selected value for this slider.
  ///
  /// The slider's thumb is drawn at a position that corresponds to this value.
72
  final double value;
73

74 75 76 77 78 79 80
  /// Called when the user selects a new value for the slider.
  ///
  /// The slider passes the new value to the callback but does not actually
  /// change state until the parent widget rebuilds the slider with the new
  /// value.
  ///
  /// If null, the slider will be displayed as disabled.
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  ///
  /// 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
  /// new Slider(
  ///   value: _duelCommandment.toDouble(),
  ///   min: 1.0,
  ///   max: 10.0,
  ///   divisions: 10,
  ///   label: '$_duelCommandment',
  ///   onChanged: (double newValue) {
  ///     setState(() {
  ///       _duelCommandment = newValue.round();
  ///     });
  ///   },
  /// ),
  /// ```
100 101
  final ValueChanged<double> onChanged;

102 103 104
  /// The minium value the user can select.
  ///
  /// Defaults to 0.0.
Hixie's avatar
Hixie committed
105
  final double min;
106 107 108 109

  /// The maximum value the user can select.
  ///
  /// Defaults to 1.0.
Hixie's avatar
Hixie committed
110
  final double max;
111

112 113 114 115 116 117 118 119 120 121 122 123
  /// The number of discrete divisions.
  ///
  /// Typically used with [label] to show the current discrete value.
  ///
  /// If null, the slider is continuous.
  final int divisions;

  /// A label to show above the slider when the slider is active.
  ///
  /// Typically used to display the value of a discrete slider.
  final String label;

124 125
  /// The color to use for the portion of the slider that has been selected.
  ///
126
  /// Defaults to accent color of the current [Theme].
127
  final Color activeColor;
128

129 130 131 132 133
  @override
  _SliderState createState() => new _SliderState();
}

class _SliderState extends State<Slider> with TickerProviderStateMixin {
Hixie's avatar
Hixie committed
134
  void _handleChanged(double value) {
135 136
    assert(config.onChanged != null);
    config.onChanged(value * (config.max - config.min) + config.min);
Hixie's avatar
Hixie committed
137 138
  }

139
  @override
140
  Widget build(BuildContext context) {
141
    assert(debugCheckHasMaterial(context));
142
    ThemeData theme = Theme.of(context);
143
    return new _SliderRenderObjectWidget(
144 145 146
      value: (config.value - config.min) / (config.max - config.min),
      divisions: config.divisions,
      label: config.label,
147 148
      activeColor: config.activeColor ?? theme.accentColor,
      textTheme: theme.primaryTextTheme,
149 150
      onChanged: config.onChanged != null ? _handleChanged : null,
      vsync: this,
151 152 153 154 155
    );
  }
}

class _SliderRenderObjectWidget extends LeafRenderObjectWidget {
156 157 158 159 160 161
  _SliderRenderObjectWidget({
    Key key,
    this.value,
    this.divisions,
    this.label,
    this.activeColor,
162
    this.textTheme,
163 164
    this.onChanged,
    this.vsync,
165
  }) : super(key: key);
166 167

  final double value;
168 169
  final int divisions;
  final String label;
170
  final Color activeColor;
171
  final TextTheme textTheme;
172
  final ValueChanged<double> onChanged;
173
  final TickerProvider vsync;
174

175
  @override
176
  _RenderSlider createRenderObject(BuildContext context) => new _RenderSlider(
177
    value: value,
178 179
    divisions: divisions,
    label: label,
180
    activeColor: activeColor,
181
    textTheme: textTheme,
182 183
    onChanged: onChanged,
    vsync: vsync,
184 185
  );

186
  @override
187
  void updateRenderObject(BuildContext context, _RenderSlider renderObject) {
188 189
    renderObject
      ..value = value
190 191
      ..divisions = divisions
      ..label = label
192
      ..activeColor = activeColor
193
      ..textTheme = textTheme
194
      ..onChanged = onChanged;
195 196
    // Ticker provider cannot change since there's a 1:1 relationship between
    // the _SliderRenderObjectWidget object and the _SliderState object.
197 198 199
  }
}

200
const double _kThumbRadius = 6.0;
201 202
const double _kActiveThumbRadius = 9.0;
const double _kDisabledThumbRadius = 4.0;
203 204
const double _kReactionRadius = 16.0;
const double _kTrackWidth = 144.0;
205 206
final Color _kInactiveTrackColor = Colors.grey[400];
final Color _kActiveTrackColor = Colors.grey[500];
207 208 209
final Tween<double> _kReactionRadiusTween = new Tween<double>(begin: _kThumbRadius, end: _kReactionRadius);
final Tween<double> _kThumbRadiusTween = new Tween<double>(begin: _kThumbRadius, end: _kActiveThumbRadius);
final ColorTween _kTrackColorTween = new ColorTween(begin: _kInactiveTrackColor, end: _kActiveTrackColor);
Adam Barth's avatar
Adam Barth committed
210
final ColorTween _kTickColorTween = new ColorTween(begin: Colors.transparent, end: Colors.black54);
211 212 213 214 215 216 217 218
final Duration _kDiscreteTransitionDuration = const Duration(milliseconds: 500);

const double _kLabelBalloonRadius = 14.0;
final Tween<double> _kLabelBalloonCenterTween = new Tween<double>(begin: 0.0, end: -_kLabelBalloonRadius * 2.0);
final Tween<double> _kLabelBalloonRadiusTween = new Tween<double>(begin: _kThumbRadius, end: _kLabelBalloonRadius);
final Tween<double> _kLabelBalloonTipTween = new Tween<double>(begin: 0.0, end: -8.0);
final double _kLabelBalloonTipAttachmentRatio = math.sin(math.PI / 4.0);

219 220
const double _kAdjustmentUnit = 0.1; // Matches iOS implementation of material slider.

221 222 223 224 225 226 227 228 229 230
double _getAdditionalHeightForLabel(String label) {
  return label == null ? 0.0 : _kLabelBalloonRadius * 2.0;
}

BoxConstraints _getAdditionalConstraints(String label) {
  return new BoxConstraints.tightFor(
    width: _kTrackWidth + 2 * _kReactionRadius,
    height: 2 * _kReactionRadius + _getAdditionalHeightForLabel(label)
  );
}
231

232
class _RenderSlider extends RenderConstrainedBox implements SemanticsActionHandler {
233 234
  _RenderSlider({
    double value,
235 236
    int divisions,
    String label,
237
    Color activeColor,
238
    TextTheme textTheme,
239 240
    this.onChanged,
    TickerProvider vsync,
241
  }) : _value = value,
242
       _divisions = divisions,
243
       _activeColor = activeColor,
244
       _textTheme = textTheme,
245
        super(additionalConstraints: _getAdditionalConstraints(label)) {
246
    assert(value != null && value >= 0.0 && value <= 1.0);
247
    this.label = label;
248
    _drag = new HorizontalDragGestureRecognizer()
249 250 251
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
      ..onEnd = _handleDragEnd;
252 253 254 255
    _reactionController = new AnimationController(
      duration: kRadialReactionDuration,
      vsync: vsync,
    );
256
    _reaction = new CurvedAnimation(
257
      parent: _reactionController,
258
      curve: Curves.fastOutSlowIn
259
    )..addListener(markNeedsPaint);
260 261
    _position = new AnimationController(
      value: value,
262 263
      duration: _kDiscreteTransitionDuration,
      vsync: vsync,
264
    )..addListener(markNeedsPaint);
265 266 267 268
  }

  double get value => _value;
  double _value;
269
  set value(double newValue) {
270 271 272 273
    assert(newValue != null && newValue >= 0.0 && newValue <= 1.0);
    if (newValue == _value)
      return;
    _value = newValue;
274
    if (divisions != null)
275
      _position.animateTo(newValue, curve: Curves.fastOutSlowIn);
276 277 278 279 280 281
    else
      _position.value = newValue;
  }

  int get divisions => _divisions;
  int _divisions;
282
  set divisions(int newDivisions) {
283 284 285 286 287 288 289 290
    if (newDivisions == _divisions)
      return;
    _divisions = newDivisions;
    markNeedsPaint();
  }

  String get label => _label;
  String _label;
291
  set label(String newLabel) {
292 293 294 295 296
    if (newLabel == _label)
      return;
    _label = newLabel;
    additionalConstraints = _getAdditionalConstraints(_label);
    if (newLabel != null) {
297 298
      // TODO(abarth): Handle textScaleFactor.
      // https://github.com/flutter/flutter/issues/5938
299 300
      _labelPainter
        ..text = new TextSpan(
301
          style: _textTheme.body1.copyWith(fontSize: 10.0),
302 303
          text: newLabel
        )
304
        ..layout();
305 306 307
    } else {
      _labelPainter.text = null;
    }
308 309 310
    markNeedsPaint();
  }

311 312
  Color get activeColor => _activeColor;
  Color _activeColor;
313
  set activeColor(Color value) {
314
    if (value == _activeColor)
315
      return;
316
    _activeColor = value;
317 318 319
    markNeedsPaint();
  }

320 321 322 323 324 325 326 327 328
  TextTheme get textTheme => _textTheme;
  TextTheme _textTheme;
  set textTheme(TextTheme value) {
    if (value == _textTheme)
      return;
    _textTheme = value;
    markNeedsPaint();
  }

329 330 331
  ValueChanged<double> onChanged;

  double get _trackLength => size.width - 2.0 * _kReactionRadius;
332

333
  Animation<double> _reaction;
334
  AnimationController _reactionController;
335

336 337 338
  AnimationController _position;
  final TextPainter _labelPainter = new TextPainter();

339 340 341 342
  HorizontalDragGestureRecognizer _drag;
  bool _active = false;
  double _currentDragValue = 0.0;

343 344 345 346 347 348 349
  double get _discretizedCurrentDragValue {
    double dragValue = _currentDragValue.clamp(0.0, 1.0);
    if (divisions != null)
      dragValue = (dragValue * divisions).round() / divisions;
    return dragValue;
  }

350 351
  bool get isInteractive => onChanged != null;

352
  void _handleDragStart(DragStartDetails details) {
353
    if (isInteractive) {
354
      _active = true;
355
      _currentDragValue = (globalToLocal(details.globalPosition).x - _kReactionRadius) / _trackLength;
356
      onChanged(_discretizedCurrentDragValue);
357
      _reactionController.forward();
358 359 360 361
      markNeedsPaint();
    }
  }

362
  void _handleDragUpdate(DragUpdateDetails details) {
363
    if (isInteractive) {
364
      _currentDragValue += details.primaryDelta / _trackLength;
365
      onChanged(_discretizedCurrentDragValue);
366 367 368
    }
  }

369
  void _handleDragEnd(DragEndDetails details) {
370 371 372
    if (_active) {
      _active = false;
      _currentDragValue = 0.0;
373
      _reactionController.reverse();
374 375 376 377
      markNeedsPaint();
    }
  }

378
  @override
379 380
  bool hitTestSelf(Point position) => true;

381
  @override
Ian Hickson's avatar
Ian Hickson committed
382
  void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
383
    assert(debugHandleEvent(event, entry));
384
    if (event is PointerDownEvent && isInteractive)
385 386 387
      _drag.addPointer(event);
  }

388
  @override
389 390 391 392
  void paint(PaintingContext context, Offset offset) {
    final Canvas canvas = context.canvas;

    final double trackLength = _trackLength;
393
    final bool enabled = isInteractive;
394
    final double value = _position.value;
395

396 397 398 399 400 401 402
    final double additionalHeightForLabel = _getAdditionalHeightForLabel(label);
    final double trackCenter = offset.dy + (size.height - additionalHeightForLabel) / 2.0 + additionalHeightForLabel;
    final double trackLeft = offset.dx + _kReactionRadius;
    final double trackTop = trackCenter - 1.0;
    final double trackBottom = trackCenter + 1.0;
    final double trackRight = trackLeft + trackLength;
    final double trackActive = trackLeft + trackLength * value;
403

404 405
    final Paint primaryPaint = new Paint()..color = enabled ? _activeColor : _kInactiveTrackColor;
    final Paint trackPaint = new Paint()..color = _kTrackColorTween.evaluate(_reaction);
406

407 408
    final Point thumbCenter = new Point(trackActive, trackCenter);
    final double thumbRadius = enabled ? _kThumbRadiusTween.evaluate(_reaction) : _kDisabledThumbRadius;
409

410
    if (enabled) {
411
      if (value > 0.0)
412
        canvas.drawRect(new Rect.fromLTRB(trackLeft, trackTop, trackActive, trackBottom), primaryPaint);
Adam Barth's avatar
Adam Barth committed
413 414 415 416 417
      if (value < 1.0) {
        final bool hasBalloon = _reaction.status != AnimationStatus.dismissed && label != null;
        final double trackActiveDelta = hasBalloon ? 0.0 : thumbRadius - 1.0;
        canvas.drawRect(new Rect.fromLTRB(trackActive + trackActiveDelta, trackTop, trackRight, trackBottom), trackPaint);
      }
418
    } else {
419 420 421 422
      if (value > 0.0)
        canvas.drawRect(new Rect.fromLTRB(trackLeft, trackTop, trackActive - _kDisabledThumbRadius - 2, trackBottom), trackPaint);
      if (value < 1.0)
        canvas.drawRect(new Rect.fromLTRB(trackActive + _kDisabledThumbRadius + 2, trackTop, trackRight, trackBottom), trackPaint);
423
    }
424

425
    if (_reaction.status != AnimationStatus.dismissed) {
426 427 428 429 430 431 432 433
      final int divisions = this.divisions;
      if (divisions != null) {
        const double tickWidth = 2.0;
        final double dx = (trackLength - tickWidth) / divisions;
        // If the ticks would be too dense, don't bother painting them.
        if (dx >= 3 * tickWidth) {
          final Paint tickPaint = new Paint()..color = _kTickColorTween.evaluate(_reaction);
          for (int i = 0; i <= divisions; i += 1) {
Adam Barth's avatar
Adam Barth committed
434
            final double left = trackLeft + i * dx;
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
            canvas.drawRect(new Rect.fromLTRB(left, trackTop, left + tickWidth, trackBottom), tickPaint);
          }
        }
      }

      if (label != null) {
        final Point center = new Point(trackActive, _kLabelBalloonCenterTween.evaluate(_reaction) + trackCenter);
        final double radius = _kLabelBalloonRadiusTween.evaluate(_reaction);
        final Point tip = new Point(trackActive, _kLabelBalloonTipTween.evaluate(_reaction) + trackCenter);
        final double tipAttachment = _kLabelBalloonTipAttachmentRatio * radius;

        canvas.drawCircle(center, radius, primaryPaint);
        Path path = new Path()
          ..moveTo(tip.x, tip.y)
          ..lineTo(center.x - tipAttachment, center.y + tipAttachment)
          ..lineTo(center.x + tipAttachment, center.y + tipAttachment)
          ..close();
        canvas.drawPath(path, primaryPaint);
        _labelPainter.layout();
        Offset labelOffset = new Offset(
          center.x - _labelPainter.width / 2.0,
          center.y - _labelPainter.height / 2.0
        );
        _labelPainter.paint(canvas, labelOffset);
        return;
      } else {
Adam Barth's avatar
Adam Barth committed
461 462
        final Color reactionBaseColor = value == 0.0 ? _kActiveTrackColor : _activeColor;
        final Paint reactionPaint = new Paint()..color = reactionBaseColor.withAlpha(kRadialReactionAlpha);
463 464
        canvas.drawCircle(thumbCenter, _kReactionRadiusTween.evaluate(_reaction), reactionPaint);
      }
465
    }
Adam Barth's avatar
Adam Barth committed
466 467 468 469 470 471 472 473 474 475 476 477

    Paint thumbPaint = primaryPaint;
    double thumbRadiusDelta = 0.0;
    if (value == 0.0) {
      thumbPaint = trackPaint;
      // This is destructive to trackPaint.
      thumbPaint
        ..style = PaintingStyle.stroke
        ..strokeWidth = 2.0;
      thumbRadiusDelta = -1.0;
    }
    canvas.drawCircle(thumbCenter, thumbRadius + thumbRadiusDelta, thumbPaint);
478
  }
479 480

  @override
481
  bool get isSemanticBoundary => isInteractive;
482 483

  @override
484
  SemanticsAnnotator get semanticsAnnotator => _annotate;
485 486 487 488

  void _annotate(SemanticsNode semantics) {
    if (isInteractive)
      semantics.addAdjustmentActions();
489 490 491
  }

  @override
492
  void performAction(SemanticsAction action) {
493
    switch (action) {
494
      case SemanticsAction.increase:
495 496 497
        if (isInteractive)
          onChanged((value + _kAdjustmentUnit).clamp(0.0, 1.0));
        break;
498
      case SemanticsAction.decrease:
499 500 501 502 503 504 505 506
        if (isInteractive)
          onChanged((value - _kAdjustmentUnit).clamp(0.0, 1.0));
        break;
      default:
        assert(false);
        break;
    }
  }
507
}