progress_indicator.dart 16.9 KB
Newer Older
1 2 3 4 5 6
// 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.

import 'dart:math' as math;

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

9
import 'material.dart';
10
import 'theme.dart';
11 12

const double _kLinearProgressIndicatorHeight = 6.0;
13 14
const double _kMinCircularProgressIndicatorSize = 36.0;
const double _kCircularProgressIndicatorStrokeWidth = 4.0;
15

16
// TODO(hansmuller): implement the support for buffer indicator
Hixie's avatar
Hixie committed
17

18 19 20 21 22 23 24 25
/// A base class for material design progress indicators
///
/// This widget cannot be instantiated directly. For a linear progress
/// indicator, see [LinearProgressIndicator]. For a circular progress indicator,
/// see [CircularProgressIndicator].
///
/// See also:
///
26
///  * <https://material.google.com/components/progress-activity.html>
27
abstract class ProgressIndicator extends StatefulWidget {
28 29 30 31 32
  /// Creates a progress indicator.
  ///
  /// The [value] argument can be either null (corresponding to an indeterminate
  /// progress indcator) or non-null (corresponding to a determinate progress
  /// indicator). See [value] for details.
33 34
  ProgressIndicator({
    Key key,
35 36 37
    this.value,
    this.backgroundColor,
    this.valueColor
38 39
  }) : super(key: key);

40 41 42 43 44 45 46 47
  /// If non-null, the value of this progress indicator with 0.0 corresponding
  /// to no progress having been made and 1.0 corresponding to all the progress
  /// having been made.
  ///
  /// If null, this progress indicator is indeterminate, which means the
  /// indicator displays a predetermined animation that does not indicator how
  /// much actual progress is being made.
  final double value;
48

49 50
  /// The progress indicator's background color. The current theme's
  /// [ThemeData.backgroundColor] by default.
51 52 53 54 55
  final Color backgroundColor;

  /// The indicator's color is the animation's value. To specify a constant
  /// color use: `new AlwaysStoppedAnimation<Color>(color)`.
  ///
56
  /// If null, the progress indicator is rendered with the current theme's
57
  /// [ThemeData.accentColor].
58 59 60
  final Animation<Color> valueColor;

  Color _getBackgroundColor(BuildContext context) => backgroundColor ?? Theme.of(context).backgroundColor;
61
  Color _getValueColor(BuildContext context) => valueColor?.value ?? Theme.of(context).accentColor;
62

63
  @override
Hixie's avatar
Hixie committed
64 65
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
66 67 68 69 70
    if (value != null) {
      description.add('${(value.clamp(0.0, 1.0) * 100.0).toStringAsFixed(1)}%');
    } else {
      description.add('<indeterminate>');
    }
Hixie's avatar
Hixie committed
71
  }
72 73
}

74 75 76 77 78
class _LinearProgressIndicatorPainter extends CustomPainter {
  const _LinearProgressIndicatorPainter({
    this.backgroundColor,
    this.valueColor,
    this.value,
79
    this.animationValue
80 81 82 83 84
  });

  final Color backgroundColor;
  final Color valueColor;
  final double value;
85
  final double animationValue;
86

87
  @override
88
  void paint(Canvas canvas, Size size) {
89
    Paint paint = new Paint()
90
      ..color = backgroundColor
91
      ..style = PaintingStyle.fill;
92 93
    canvas.drawRect(Point.origin & size, paint);

94
    paint.color = valueColor;
95 96 97 98
    if (value != null) {
      double width = value.clamp(0.0, 1.0) * size.width;
      canvas.drawRect(Point.origin & new Size(width, size.height), paint);
    } else {
99
      double startX = size.width * (1.5 * animationValue - 0.5);
100 101 102 103 104 105 106
      double endX = startX + 0.5 * size.width;
      double x = startX.clamp(0.0, size.width);
      double width = endX.clamp(0.0, size.width) - x;
      canvas.drawRect(new Point(x, 0.0) & new Size(width, size.height), paint);
    }
  }

107
  @override
108 109 110 111
  bool shouldRepaint(_LinearProgressIndicatorPainter oldPainter) {
    return oldPainter.backgroundColor != backgroundColor
        || oldPainter.valueColor != valueColor
        || oldPainter.value != value
112
        || oldPainter.animationValue != animationValue;
113 114 115
  }
}

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
/// A material design linear progress indicator.
///
/// A widget that shows progress along a line. There are two kinds of linear
/// progress indicators:
///
///  * _Determinate_. Determinate progress indicators have a specific value at
///    each point in time, and the value should increase monotonically from 0.0
///    to 1.0, at which time the indicator is complete. To create a determinate
///    progress indicator, use a non-null [value] between 0.0 and 1.0.
///  * _Indeterminate_. Indeterminate progress indicators do not have a specific
///    value at each point in time and instead indicate that progress is being
///    made without indicating how much progress remains. To create an
///    indeterminate progress indicator, use a null [value].
///
/// See also:
///
///  * [CircularProgressIndicator]
133
///  * <https://material.google.com/components/progress-activity.html#progress-activity-types-of-indicators>
134
class LinearProgressIndicator extends ProgressIndicator {
135 136 137 138 139
  /// Creates a linear progress indicator.
  ///
  /// The [value] argument can be either null (corresponding to an indeterminate
  /// progress indcator) or non-null (corresponding to a determinate progress
  /// indicator). See [value] for details.
140 141 142 143 144
  LinearProgressIndicator({
    Key key,
    double value
  }) : super(key: key, value: value);

145
  @override
146
  _LinearProgressIndicatorState createState() => new _LinearProgressIndicatorState();
147 148
}

149
class _LinearProgressIndicatorState extends State<LinearProgressIndicator> with SingleTickerProviderStateMixin {
150 151 152
  Animation<double> _animation;
  AnimationController _controller;

153
  @override
154 155 156
  void initState() {
    super.initState();
    _controller = new AnimationController(
157 158
      duration: const Duration(milliseconds: 1500),
      vsync: this,
159 160 161 162
    )..repeat();
    _animation = new CurvedAnimation(parent: _controller, curve: Curves.fastOutSlowIn);
  }

163
  @override
164
  void dispose() {
165
    _controller.dispose();
166 167 168
    super.dispose();
  }

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
  Widget _buildIndicator(BuildContext context, double animationValue) {
    return new Container(
      constraints: new BoxConstraints.tightFor(
        width: double.INFINITY,
        height: _kLinearProgressIndicatorHeight
      ),
      child: new CustomPaint(
        painter: new _LinearProgressIndicatorPainter(
          backgroundColor: config._getBackgroundColor(context),
          valueColor: config._getValueColor(context),
          value: config.value, // may be null
          animationValue: animationValue // ignored if config.value is not null
        )
      )
    );
  }

186
  @override
187 188
  Widget build(BuildContext context) {
    if (config.value != null)
189
      return _buildIndicator(context, _animation.value);
190 191 192 193

    return new AnimatedBuilder(
      animation: _animation,
      builder: (BuildContext context, Widget child) {
194
        return _buildIndicator(context, _animation.value);
195 196 197 198 199
      }
    );
  }
}

200
class _CircularProgressIndicatorPainter extends CustomPainter {
201 202
  static const double _kTwoPI = math.PI * 2.0;
  static const double _kEpsilon = .001;
203
  // Canavs.drawArc(r, 0, 2*PI) doesn't draw anything, so just get close.
204 205
  static const double _kSweep = _kTwoPI - _kEpsilon;
  static const double _kStartAngle = -math.PI / 2.0;
206

207
  _CircularProgressIndicatorPainter({
208
    this.valueColor,
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    double value,
    double headValue,
    double tailValue,
    int stepValue,
    double rotationValue,
    this.strokeWidth
  }) : this.value = value,
       this.headValue = headValue,
       this.tailValue = tailValue,
       this.stepValue = stepValue,
       this.rotationValue = rotationValue,
       arcStart = value != null
         ? _kStartAngle
         : _kStartAngle + tailValue * 3 / 2 * math.PI + rotationValue * math.PI * 1.7 - stepValue * 0.8 * math.PI,
       arcSweep = value != null
         ? value.clamp(0.0, 1.0) * _kSweep
         : math.max(headValue * 3 / 2 * math.PI - tailValue * 3 / 2 * math.PI, _kEpsilon);
226 227 228

  final Color valueColor;
  final double value;
229 230 231 232
  final double headValue;
  final double tailValue;
  final int stepValue;
  final double rotationValue;
233 234 235
  final double strokeWidth;
  final double arcStart;
  final double arcSweep;
236

237
  @override
238
  void paint(Canvas canvas, Size size) {
239
    Paint paint = new Paint()
240
      ..color = valueColor
241
      ..strokeWidth = strokeWidth
242
      ..style = PaintingStyle.stroke;
243

244
    if (value == null) // Indeterminate
245
      paint.strokeCap = StrokeCap.square;
246

247
    canvas.drawArc(Point.origin & size, arcStart, arcSweep, false, paint);
248 249
  }

250
  @override
251
  bool shouldRepaint(_CircularProgressIndicatorPainter oldPainter) {
252 253
    return oldPainter.valueColor != valueColor
        || oldPainter.value != value
254 255 256
        || oldPainter.headValue != headValue
        || oldPainter.tailValue != tailValue
        || oldPainter.stepValue != stepValue
257 258
        || oldPainter.rotationValue != rotationValue
        || oldPainter.strokeWidth != strokeWidth;
259 260 261
  }
}

262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
/// A material design circular progress indicator.
///
/// A widget that shows progress along a circle. There are two kinds of circular
/// progress indicators:
///
///  * _Determinate_. Determinate progress indicators have a specific value at
///    each point in time, and the value should increase monotonically from 0.0
///    to 1.0, at which time the indicator is complete. To create a determinate
///    progress indicator, use a non-null [value] between 0.0 and 1.0.
///  * _Indeterminate_. Indeterminate progress indicators do not have a specific
///    value at each point in time and instead indicate that progress is being
///    made without indicating how much progress remains. To create an
///    indeterminate progress indicator, use a null [value].
///
/// See also:
///
///  * [LinearProgressIndicator]
279
///  * <https://material.google.com/components/progress-activity.html#progress-activity-types-of-indicators>
280
class CircularProgressIndicator extends ProgressIndicator {
281 282 283 284 285
  /// Creates a circular progress indicator.
  ///
  /// The [value] argument can be either null (corresponding to an indeterminate
  /// progress indcator) or non-null (corresponding to a determinate progress
  /// indicator). See [value] for details.
286 287
  CircularProgressIndicator({
    Key key,
288 289 290 291
    double value,
    Color backgroundColor,
    Animation<Color> valueColor
  }) : super(key: key, value: value, backgroundColor: backgroundColor, valueColor: valueColor);
292

293
  @override
294
  _CircularProgressIndicatorState createState() => new _CircularProgressIndicatorState();
295
}
296

297
// Tweens used by circular progress indicator
Hixie's avatar
Hixie committed
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
final Animatable<double> _kStrokeHeadTween = new CurveTween(
  curve: new Interval(0.0, 0.5, curve: Curves.fastOutSlowIn)
).chain(new CurveTween(
  curve: new SawTooth(5)
));

final Animatable<double> _kStrokeTailTween = new CurveTween(
  curve: new Interval(0.5, 1.0, curve: Curves.fastOutSlowIn)
).chain(new CurveTween(
  curve: new SawTooth(5)
));

final Animatable<int> _kStepTween = new StepTween(begin: 0, end: 5);

final Animatable<double> _kRotationTween = new CurveTween(curve: new SawTooth(5));
313

314
class _CircularProgressIndicatorState extends State<CircularProgressIndicator> with SingleTickerProviderStateMixin {
315
  AnimationController _controller;
316

317
  @override
318 319
  void initState() {
    super.initState();
320 321 322 323
    _controller = new AnimationController(
      duration: const Duration(milliseconds: 6666),
      vsync: this,
    )..repeat();
324 325
  }

326
  @override
327
  void dispose() {
328
    _controller.dispose();
329 330 331
    super.dispose();
  }

332 333 334 335 336 337 338 339 340 341 342 343 344
  Widget _buildIndicator(BuildContext context, double headValue, double tailValue, int stepValue, double rotationValue) {
    return new Container(
      constraints: new BoxConstraints(
        minWidth: _kMinCircularProgressIndicatorSize,
        minHeight: _kMinCircularProgressIndicatorSize
      ),
      child: new CustomPaint(
        painter: new _CircularProgressIndicatorPainter(
          valueColor: config._getValueColor(context),
          value: config.value, // may be null
          headValue: headValue, // remaining arguments are ignored if config.value is not null
          tailValue: tailValue,
          stepValue: stepValue,
345 346
          rotationValue: rotationValue,
          strokeWidth: _kCircularProgressIndicatorStrokeWidth
347 348 349 350 351
        )
      )
    );
  }

352
  Widget _buildAnimation() {
353
    return new AnimatedBuilder(
354
      animation: _controller,
355
      builder: (BuildContext context, Widget child) {
356 357
        return _buildIndicator(
          context,
358 359 360 361
          _kStrokeHeadTween.evaluate(_controller),
          _kStrokeTailTween.evaluate(_controller),
          _kStepTween.evaluate(_controller),
          _kRotationTween.evaluate(_controller)
362
        );
363 364 365
      }
    );
  }
366 367 368 369 370 371 372

  @override
  Widget build(BuildContext context) {
    if (config.value != null)
      return _buildIndicator(context, 0.0, 0.0, 0, 0.0);
    return _buildAnimation();
  }
373
}
374 375 376 377 378 379 380 381 382

class _RefreshProgressIndicatorPainter extends _CircularProgressIndicatorPainter {
  _RefreshProgressIndicatorPainter({
    Color valueColor,
    double value,
    double headValue,
    double tailValue,
    int stepValue,
    double rotationValue,
383 384
    double strokeWidth,
    this.arrowheadScale
385 386 387 388 389 390 391 392 393 394
  }) : super(
    valueColor: valueColor,
    value: value,
    headValue: headValue,
    tailValue: tailValue,
    stepValue: stepValue,
    rotationValue: rotationValue,
    strokeWidth: strokeWidth
  );

395 396
  final double arrowheadScale;

397 398
  void paintArrowhead(Canvas canvas, Size size) {
    // ux, uy: a unit vector whose direction parallels the base of the arrowhead.
399
    // Note that ux, -uy points in the direction the arrowhead points.
400 401 402 403 404 405
    final double arcEnd = arcStart + arcSweep;
    final double ux = math.cos(arcEnd);
    final double uy = math.sin(arcEnd);

    assert(size.width == size.height);
    final double radius = size.width / 2.0;
406 407 408 409 410
    final double arrowheadPointX = radius + ux * radius + -uy * strokeWidth * 2.0 * arrowheadScale;
    final double arrowheadPointY = radius + uy * radius +  ux * strokeWidth * 2.0 * arrowheadScale;
    final double arrowheadRadius = strokeWidth * 1.5 * arrowheadScale;
    final double innerRadius = radius - arrowheadRadius;
    final double outerRadius = radius + arrowheadRadius;
411 412 413 414

    Path path = new Path()
      ..moveTo(radius + ux * innerRadius, radius + uy * innerRadius)
      ..lineTo(radius + ux * outerRadius, radius + uy * outerRadius)
415
      ..lineTo(arrowheadPointX, arrowheadPointY)
416 417 418 419 420 421 422 423 424 425 426
      ..close();
    Paint paint = new Paint()
      ..color = valueColor
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.fill;
    canvas.drawPath(path, paint);
  }

  @override
  void paint(Canvas canvas, Size size) {
    super.paint(canvas, size);
427 428
    if (arrowheadScale > 0.0)
      paintArrowhead(canvas, size);
429 430 431
  }
}

432 433 434 435 436 437 438 439 440
/// An indicator for the progress of refreshing the contents of a widget.
///
/// Typically used for swipe-to-refresh interactions. See [RefreshIndicator] for
/// a complete implementation of swipe-to-refresh driven by a [Scrollable]
/// widget.
///
/// See also:
///
///  * [RefreshIndicator]
441
class RefreshProgressIndicator extends CircularProgressIndicator {
442 443 444 445
  /// Creates a refresh progress indicator.
  ///
  /// Rather than creating a refresh progress indicator directly, consider using
  /// a [RefreshIndicator] together with a [Scrollable] widget.
446 447 448 449 450
  RefreshProgressIndicator({
    Key key,
    double value,
    Color backgroundColor,
    Animation<Color> valueColor
451 452 453 454 455 456
  }) : super(
    key: key,
    value: value,
    backgroundColor: backgroundColor,
    valueColor: valueColor
  );
457 458 459 460 461 462 463 464

  @override
  _RefreshProgressIndicatorState createState() => new _RefreshProgressIndicatorState();
}

class _RefreshProgressIndicatorState extends _CircularProgressIndicatorState {
  static double _kIndicatorSize = 40.0;

465 466 467 468 469 470 471 472 473 474 475 476 477
  // Always show the indeterminate version of the circular progress indicator.
  // When value is non-null the sweep of the progress indicator arrow's arc
  // varies from 0 to about 270 degrees. When value is null the arrow animates
  // starting from wherever we left it.
  @override
  Widget build(BuildContext context) {
    if (config.value != null)
      _controller.value = config.value / 10.0;
    else
      _controller.forward();
    return _buildAnimation();
  }

478 479
  @override
  Widget _buildIndicator(BuildContext context, double headValue, double tailValue, int stepValue, double rotationValue) {
480
    final double arrowheadScale = config.value == null ? 0.0 : (config.value * 2.0).clamp(0.0, 1.0);
481 482 483 484 485 486
    return new Container(
      width: _kIndicatorSize,
      height: _kIndicatorSize,
      margin: const EdgeInsets.all(4.0), // acommodate the shadow
      child: new Material(
        type: MaterialType.circle,
487
        color: config.backgroundColor ?? Theme.of(context).canvasColor,
488 489 490 491 492 493
        elevation: 2,
        child: new Padding(
          padding: const EdgeInsets.all(12.0),
          child: new CustomPaint(
            painter: new _RefreshProgressIndicatorPainter(
              valueColor: config._getValueColor(context),
494 495
              value: null, // Draw the indeterminate progress indicator.
              headValue: headValue,
496 497 498
              tailValue: tailValue,
              stepValue: stepValue,
              rotationValue: rotationValue,
499 500
              strokeWidth: 2.0,
              arrowheadScale: arrowheadScale
501 502 503 504 505 506 507
            )
          )
        )
      )
    );
  }
}