progress_indicator.dart 26.2 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// 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/cupertino.dart';
8
import 'package:flutter/foundation.dart';
9
import 'package:flutter/widgets.dart';
10

11
import 'material.dart';
12
import 'theme.dart';
13

14
const double _kMinCircularProgressIndicatorSize = 36.0;
15
const int _kIndeterminateLinearDuration = 1800;
16
const int _kIndeterminateCircularDuration = 1333 * 2222;
17

18 19
enum _ActivityIndicatorType { material, adaptive }

20
/// A base class for material design progress indicators.
21 22 23 24 25 26 27
///
/// This widget cannot be instantiated directly. For a linear progress
/// indicator, see [LinearProgressIndicator]. For a circular progress indicator,
/// see [CircularProgressIndicator].
///
/// See also:
///
28
///  * <https://material.io/design/components/progress-indicators.html>
29
abstract class ProgressIndicator extends StatefulWidget {
30 31
  /// Creates a progress indicator.
  ///
32 33 34 35
  /// {@template flutter.material.progressIndicator.parameters}
  /// The [value] argument can either be null for an indeterminate
  /// progress indicator, or non-null for a determinate progress
  /// indicator.
36 37 38 39 40 41 42
  ///
  /// ## Accessibility
  ///
  /// The [semanticsLabel] can be used to identify the purpose of this progress
  /// bar for screen reading software. The [semanticsValue] property may be used
  /// for determinate progress indicators to indicate how much progress has been made.
  /// {@endtemplate}
43
  const ProgressIndicator({
44
    Key? key,
45 46
    this.value,
    this.backgroundColor,
47
    this.valueColor,
48 49
    this.semanticsLabel,
    this.semanticsValue,
50 51
  }) : super(key: key);

52 53 54
  /// If non-null, the value of this progress indicator.
  ///
  /// A value of 0.0 means no progress and 1.0 means that progress is complete.
55 56
  ///
  /// If null, this progress indicator is indeterminate, which means the
57
  /// indicator displays a predetermined animation that does not indicate how
58
  /// much actual progress is being made.
59 60 61
  ///
  /// This property is ignored if used in an adaptive constructor inside an iOS
  /// environment.
62
  final double? value;
63

64 65 66
  /// The progress indicator's background color.
  ///
  /// The current theme's [ThemeData.backgroundColor] by default.
67 68 69
  ///
  /// This property is ignored if used in an adaptive constructor inside an iOS
  /// environment.
70
  final Color? backgroundColor;
71

72 73 74
  /// The progress indicator's color as an animated value.
  ///
  /// To specify a constant color use: `AlwaysStoppedAnimation<Color>(color)`.
75
  ///
76
  /// If null, the progress indicator is rendered with the current theme's
77
  /// [ThemeData.accentColor].
78 79 80
  ///
  /// This property is ignored if used in an adaptive constructor inside an iOS
  /// environment.
81
  final Animation<Color?>? valueColor;
82

83
  /// {@template flutter.material.progressIndicator.semanticsLabel}
84
  /// The [SemanticsProperties.label] for this progress indicator.
85 86 87 88
  ///
  /// This value indicates the purpose of the progress bar, and will be
  /// read out by screen readers to indicate the purpose of this progress
  /// indicator.
89 90 91
  ///
  /// This property is ignored if used in an adaptive constructor inside an iOS
  /// environment.
92
  /// {@endtemplate}
93
  final String? semanticsLabel;
94 95

  /// {@template flutter.material.progressIndicator.semanticsValue}
96
  /// The [SemanticsProperties.value] for this progress indicator.
97 98 99 100 101 102
  ///
  /// This will be used in conjunction with the [semanticsLabel] by
  /// screen reading software to identify the widget, and is primarily
  /// intended for use with determinate progress indicators to announce
  /// how far along they are.
  ///
103 104 105
  /// For determinate progress indicators, this will be defaulted to
  /// [ProgressIndicator.value] expressed as a percentage, i.e. `0.1` will
  /// become '10%'.
106 107 108
  ///
  /// This property is ignored if used in an adaptive constructor inside an iOS
  /// environment.
109
  /// {@endtemplate}
110
  final String? semanticsValue;
111

112 113
  Color _getBackgroundColor(BuildContext context) => backgroundColor ?? Theme.of(context)!.backgroundColor;
  Color _getValueColor(BuildContext context) => valueColor?.value ?? Theme.of(context)!.accentColor;
114

115
  @override
116 117
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
118
    properties.add(PercentProperty('value', value, showName: false, ifNull: '<indeterminate>'));
Hixie's avatar
Hixie committed
119
  }
120 121

  Widget _buildSemanticsWrapper({
122 123
    required BuildContext context,
    required Widget child,
124
  }) {
125
    String? expandedSemanticsValue = semanticsValue;
126
    if (value != null) {
127
      expandedSemanticsValue ??= '${(value! * 100).round()}%';
128 129 130 131 132 133 134
    }
    return Semantics(
      label: semanticsLabel,
      value: expandedSemanticsValue,
      child: child,
    );
  }
135 136
}

137
class _LinearProgressIndicatorPainter extends CustomPainter {
138
  const _LinearProgressIndicatorPainter({
139 140
    required this.backgroundColor,
    required this.valueColor,
141
    this.value,
142 143
    required this.animationValue,
    required this.textDirection,
144 145 146 147
  }) : assert(textDirection != null);

  final Color backgroundColor;
  final Color valueColor;
148
  final double? value;
149 150 151
  final double animationValue;
  final TextDirection textDirection;

152 153
  // The indeterminate progress animation displays two lines whose leading (head)
  // and trailing (tail) endpoints are defined by the following four curves.
154
  static const Curve line1Head = Interval(
155 156
    0.0,
    750.0 / _kIndeterminateLinearDuration,
157
    curve: Cubic(0.2, 0.0, 0.8, 1.0),
158
  );
159
  static const Curve line1Tail = Interval(
160 161
    333.0 / _kIndeterminateLinearDuration,
    (333.0 + 750.0) / _kIndeterminateLinearDuration,
162
    curve: Cubic(0.4, 0.0, 1.0, 1.0),
163
  );
164
  static const Curve line2Head = Interval(
165 166
    1000.0 / _kIndeterminateLinearDuration,
    (1000.0 + 567.0) / _kIndeterminateLinearDuration,
167
    curve: Cubic(0.0, 0.0, 0.65, 1.0),
168
  );
169
  static const Curve line2Tail = Interval(
170 171
    1267.0 / _kIndeterminateLinearDuration,
    (1267.0 + 533.0) / _kIndeterminateLinearDuration,
172
    curve: Cubic(0.10, 0.0, 0.45, 1.0),
173 174
  );

175
  @override
176
  void paint(Canvas canvas, Size size) {
177
    final Paint paint = Paint()
178
      ..color = backgroundColor
179
      ..style = PaintingStyle.fill;
180
    canvas.drawRect(Offset.zero & size, paint);
181

182
    paint.color = valueColor;
183

184 185 186
    void drawBar(double x, double width) {
      if (width <= 0.0)
        return;
187

188
      final double left;
189 190 191 192 193 194 195 196
      switch (textDirection) {
        case TextDirection.rtl:
          left = size.width - width - x;
          break;
        case TextDirection.ltr:
          left = x;
          break;
      }
197
      canvas.drawRect(Offset(left, 0.0) & Size(width, size.height), paint);
198
    }
199 200

    if (value != null) {
201
      drawBar(0.0, value!.clamp(0.0, 1.0) * size.width);
202 203 204 205 206 207 208 209 210 211
    } else {
      final double x1 = size.width * line1Tail.transform(animationValue);
      final double width1 = size.width * line1Head.transform(animationValue) - x1;

      final double x2 = size.width * line2Tail.transform(animationValue);
      final double width2 = size.width * line2Head.transform(animationValue) - x2;

      drawBar(x1, width1);
      drawBar(x2, width2);
    }
212 213
  }

214
  @override
215 216 217 218
  bool shouldRepaint(_LinearProgressIndicatorPainter oldPainter) {
    return oldPainter.backgroundColor != backgroundColor
        || oldPainter.valueColor != valueColor
        || oldPainter.value != value
219 220
        || oldPainter.animationValue != animationValue
        || oldPainter.textDirection != textDirection;
221 222 223
  }
}

224
/// A material design linear progress indicator, also known as a progress bar.
225
///
226 227
/// {@youtube 560 315 https://www.youtube.com/watch?v=O-rhXZLtpv0}
///
228 229 230 231 232 233 234 235 236 237 238 239
/// 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].
///
240 241 242
/// The indicator line is displayed with [valueColor], an animated value. To
/// specify a constant color value use: `AlwaysStoppedAnimation<Color>(color)`.
///
243 244 245
/// The minimum height of the indicator can be specified using [minHeight].
/// The indicator can be made taller by wrapping the widget with a [SizedBox].
///
246 247
/// See also:
///
248 249 250
///  * [CircularProgressIndicator], which shows progress along a circular arc.
///  * [RefreshIndicator], which automatically displays a [CircularProgressIndicator]
///    when the underlying vertical scrollable is overscrolled.
251
///  * <https://material.io/design/components/progress-indicators.html#linear-progress-indicators>
252
class LinearProgressIndicator extends ProgressIndicator {
253 254
  /// Creates a linear progress indicator.
  ///
255
  /// {@macro flutter.material.progressIndicator.parameters}
256
  const LinearProgressIndicator({
257 258 259 260
    Key? key,
    double? value,
    Color? backgroundColor,
    Animation<Color>? valueColor,
261
    this.minHeight,
262 263
    String? semanticsLabel,
    String? semanticsValue,
264 265 266 267 268 269 270 271 272 273 274 275 276
  }) : assert(minHeight == null || minHeight > 0),
       super(
        key: key,
        value: value,
        backgroundColor: backgroundColor,
        valueColor: valueColor,
        semanticsLabel: semanticsLabel,
        semanticsValue: semanticsValue,
      );

  /// The minimum height of the line used to draw the indicator.
  ///
  /// This defaults to 4dp.
277
  final double? minHeight;
278

279
  @override
280
  _LinearProgressIndicatorState createState() => _LinearProgressIndicatorState();
281 282
}

283
class _LinearProgressIndicatorState extends State<LinearProgressIndicator> with SingleTickerProviderStateMixin {
284
  late AnimationController _controller;
285

286
  @override
287 288
  void initState() {
    super.initState();
289
    _controller = AnimationController(
290
      duration: const Duration(milliseconds: _kIndeterminateLinearDuration),
291
      vsync: this,
292 293 294 295 296 297 298 299 300 301 302 303
    );
    if (widget.value == null)
      _controller.repeat();
  }

  @override
  void didUpdateWidget(LinearProgressIndicator oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.value == null && !_controller.isAnimating)
      _controller.repeat();
    else if (widget.value != null && _controller.isAnimating)
      _controller.stop();
304 305
  }

306
  @override
307
  void dispose() {
308
    _controller.dispose();
309 310 311
    super.dispose();
  }

312
  Widget _buildIndicator(BuildContext context, double animationValue, TextDirection textDirection) {
313 314 315
    return widget._buildSemanticsWrapper(
      context: context,
      child: Container(
316
        constraints: BoxConstraints(
317
          minWidth: double.infinity,
318
          minHeight: widget.minHeight ?? 4.0,
319 320 321 322 323 324 325 326 327
        ),
        child: CustomPaint(
          painter: _LinearProgressIndicatorPainter(
            backgroundColor: widget._getBackgroundColor(context),
            valueColor: widget._getValueColor(context),
            value: widget.value, // may be null
            animationValue: animationValue, // ignored if widget.value is not null
            textDirection: textDirection,
          ),
328 329
        ),
      ),
330 331 332
    );
  }

333
  @override
334
  Widget build(BuildContext context) {
335
    final TextDirection textDirection = Directionality.of(context)!;
336

337
    if (widget.value != null)
338
      return _buildIndicator(context, _controller.value, textDirection);
339

340
    return AnimatedBuilder(
341
      animation: _controller.view,
342
      builder: (BuildContext context, Widget? child) {
343
        return _buildIndicator(context, _controller.value, textDirection);
344
      },
345 346 347 348
    );
  }
}

349
class _CircularProgressIndicatorPainter extends CustomPainter {
350
  _CircularProgressIndicatorPainter({
351
    this.backgroundColor,
352 353 354 355 356 357 358
    required this.valueColor,
    required this.value,
    required this.headValue,
    required this.tailValue,
    required this.offsetValue,
    required this.rotationValue,
    required this.strokeWidth,
359
  }) : arcStart = value != null
360
         ? _startAngle
361
         : _startAngle + tailValue * 3 / 2 * math.pi + rotationValue * math.pi * 2.0 + offsetValue * 0.5 * math.pi,
362
       arcSweep = value != null
363
         ? value.clamp(0.0, 1.0) * _sweep
364
         : math.max(headValue * 3 / 2 * math.pi - tailValue * 3 / 2 * math.pi, _epsilon);
365

366
  final Color? backgroundColor;
367
  final Color valueColor;
368
  final double? value;
369 370
  final double headValue;
  final double tailValue;
371
  final double offsetValue;
372
  final double rotationValue;
373 374 375
  final double strokeWidth;
  final double arcStart;
  final double arcSweep;
376

377 378 379 380 381 382
  static const double _twoPi = math.pi * 2.0;
  static const double _epsilon = .001;
  // Canvas.drawArc(r, 0, 2*PI) doesn't draw anything, so just get close.
  static const double _sweep = _twoPi - _epsilon;
  static const double _startAngle = -math.pi / 2.0;

383
  @override
384
  void paint(Canvas canvas, Size size) {
385
    final Paint paint = Paint()
386
      ..color = valueColor
387
      ..strokeWidth = strokeWidth
388
      ..style = PaintingStyle.stroke;
389 390
    if (backgroundColor != null) {
      final Paint backgroundPaint = Paint()
391
        ..color = backgroundColor!
392 393 394 395
        ..strokeWidth = strokeWidth
        ..style = PaintingStyle.stroke;
      canvas.drawArc(Offset.zero & size, 0, _sweep, false, backgroundPaint);
    }
396

397
    if (value == null) // Indeterminate
398
      paint.strokeCap = StrokeCap.square;
399

400
    canvas.drawArc(Offset.zero & size, arcStart, arcSweep, false, paint);
401 402
  }

403
  @override
404
  bool shouldRepaint(_CircularProgressIndicatorPainter oldPainter) {
405 406
    return oldPainter.backgroundColor != backgroundColor
        || oldPainter.valueColor != valueColor
407
        || oldPainter.value != value
408 409
        || oldPainter.headValue != headValue
        || oldPainter.tailValue != tailValue
410
        || oldPainter.offsetValue != offsetValue
411 412
        || oldPainter.rotationValue != rotationValue
        || oldPainter.strokeWidth != strokeWidth;
413 414 415
  }
}

416 417
/// A material design circular progress indicator, which spins to indicate that
/// the application is busy.
418
///
419 420
/// {@youtube 560 315 https://www.youtube.com/watch?v=O-rhXZLtpv0}
///
421 422 423 424 425 426 427 428 429 430 431 432
/// 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].
///
433 434 435
/// The indicator arc is displayed with [valueColor], an animated value. To
/// specify a constant color use: `AlwaysStoppedAnimation<Color>(color)`.
///
436 437
/// See also:
///
438 439 440
///  * [LinearProgressIndicator], which displays progress along a line.
///  * [RefreshIndicator], which automatically displays a [CircularProgressIndicator]
///    when the underlying vertical scrollable is overscrolled.
441
///  * <https://material.io/design/components/progress-indicators.html#circular-progress-indicators>
442
class CircularProgressIndicator extends ProgressIndicator {
443 444
  /// Creates a circular progress indicator.
  ///
445
  /// {@macro flutter.material.progressIndicator.parameters}
446
  const CircularProgressIndicator({
447 448 449 450
    Key? key,
    double? value,
    Color? backgroundColor,
    Animation<Color?>? valueColor,
451
    this.strokeWidth = 4.0,
452 453
    String? semanticsLabel,
    String? semanticsValue,
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
  }) : _indicatorType = _ActivityIndicatorType.material,
       super(
         key: key,
         value: value,
         backgroundColor: backgroundColor,
         valueColor: valueColor,
         semanticsLabel: semanticsLabel,
         semanticsValue: semanticsValue,
       );

  /// Creates an adaptive progress indicator that is a
  /// [CupertinoActivityIndicator] in iOS and [CircularProgressIndicator] in
  /// material theme/non-iOS.
  ///
  /// The [value], [backgroundColor], [valueColor], [strokeWidth],
  /// [semanticsLabel], and [semanticsValue] will be ignored in iOS.
  ///
  /// {@macro flutter.material.progressIndicator.parameters}
  const CircularProgressIndicator.adaptive({
    Key? key,
    double? value,
    Color? backgroundColor,
    Animation<Color?>? valueColor,
    this.strokeWidth = 4.0,
    String? semanticsLabel,
    String? semanticsValue,
  }) : _indicatorType = _ActivityIndicatorType.adaptive,
       super(
482 483 484 485 486 487 488
         key: key,
         value: value,
         backgroundColor: backgroundColor,
         valueColor: valueColor,
         semanticsLabel: semanticsLabel,
         semanticsValue: semanticsValue,
       );
489

490 491
  final _ActivityIndicatorType _indicatorType;

492
  /// The width of the line used to draw the circle.
493 494 495
  ///
  /// This property is ignored if used in an adaptive constructor inside an iOS
  /// environment.
496 497
  final double strokeWidth;

498
  @override
499
  _CircularProgressIndicatorState createState() => _CircularProgressIndicatorState();
500
}
501

502
class _CircularProgressIndicatorState extends State<CircularProgressIndicator> with SingleTickerProviderStateMixin {
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
  static const int _pathCount = _kIndeterminateCircularDuration ~/ 1333;
  static const int _rotationCount = _kIndeterminateCircularDuration ~/ 2222;

  static final Animatable<double> _strokeHeadTween = CurveTween(
    curve: const Interval(0.0, 0.5, curve: Curves.fastOutSlowIn),
  ).chain(CurveTween(
    curve: const SawTooth(_pathCount),
  ));
  static final Animatable<double> _strokeTailTween = CurveTween(
    curve: const Interval(0.5, 1.0, curve: Curves.fastOutSlowIn),
  ).chain(CurveTween(
    curve: const SawTooth(_pathCount),
  ));
  static final Animatable<double> _offsetTween = CurveTween(curve: const SawTooth(_pathCount));
  static final Animatable<double> _rotationTween = CurveTween(curve: const SawTooth(_rotationCount));

519
  late AnimationController _controller;
520

521
  @override
522 523
  void initState() {
    super.initState();
524
    _controller = AnimationController(
525
      duration: const Duration(milliseconds: _kIndeterminateCircularDuration),
526
      vsync: this,
527 528 529 530 531 532 533 534 535 536 537 538
    );
    if (widget.value == null)
      _controller.repeat();
  }

  @override
  void didUpdateWidget(CircularProgressIndicator oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.value == null && !_controller.isAnimating)
      _controller.repeat();
    else if (widget.value != null && _controller.isAnimating)
      _controller.stop();
539 540
  }

541
  @override
542
  void dispose() {
543
    _controller.dispose();
544 545 546
    super.dispose();
  }

547 548 549 550 551
  Widget _buildCupertinoIndicator(BuildContext context) {
    return CupertinoActivityIndicator(key: widget.key);
  }

  Widget _buildMaterialIndicator(BuildContext context, double headValue, double tailValue, double offsetValue, double rotationValue) {
552 553 554 555 556 557 558 559 560
    return widget._buildSemanticsWrapper(
      context: context,
      child: Container(
        constraints: const BoxConstraints(
          minWidth: _kMinCircularProgressIndicatorSize,
          minHeight: _kMinCircularProgressIndicatorSize,
        ),
        child: CustomPaint(
          painter: _CircularProgressIndicatorPainter(
561
            backgroundColor: widget.backgroundColor,
562 563 564 565
            valueColor: widget._getValueColor(context),
            value: widget.value, // may be null
            headValue: headValue, // remaining arguments are ignored if widget.value is not null
            tailValue: tailValue,
566
            offsetValue: offsetValue,
567 568 569
            rotationValue: rotationValue,
            strokeWidth: widget.strokeWidth,
          ),
570 571
        ),
      ),
572 573 574
    );
  }

575
  Widget _buildAnimation() {
576
    return AnimatedBuilder(
577
      animation: _controller,
578
      builder: (BuildContext context, Widget? child) {
579
        return _buildMaterialIndicator(
580
          context,
581 582 583 584
          _strokeHeadTween.evaluate(_controller),
          _strokeTailTween.evaluate(_controller),
          _offsetTween.evaluate(_controller),
          _rotationTween.evaluate(_controller),
585
        );
586
      },
587 588
    );
  }
589 590 591

  @override
  Widget build(BuildContext context) {
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
    switch (widget._indicatorType) {
      case _ActivityIndicatorType.material:
        if (widget.value != null)
          return _buildMaterialIndicator(context, 0.0, 0.0, 0, 0.0);
        return _buildAnimation();
      case _ActivityIndicatorType.adaptive:
        final ThemeData theme = Theme.of(context)!;
        assert(theme.platform != null);
        switch (theme.platform) {
          case TargetPlatform.iOS:
          case TargetPlatform.macOS:
            return _buildCupertinoIndicator(context);
          case TargetPlatform.android:
          case TargetPlatform.fuchsia:
          case TargetPlatform.linux:
          case TargetPlatform.windows:
            if (widget.value != null)
              return _buildMaterialIndicator(context, 0.0, 0.0, 0, 0.0);
            return _buildAnimation();
        }
    }
613
  }
614
}
615 616 617

class _RefreshProgressIndicatorPainter extends _CircularProgressIndicatorPainter {
  _RefreshProgressIndicatorPainter({
618 619 620 621 622 623 624 625
    required Color valueColor,
    required double? value,
    required double headValue,
    required double tailValue,
    required double offsetValue,
    required double rotationValue,
    required double strokeWidth,
    required this.arrowheadScale,
626 627 628 629 630
  }) : super(
    valueColor: valueColor,
    value: value,
    headValue: headValue,
    tailValue: tailValue,
631
    offsetValue: offsetValue,
632
    rotationValue: rotationValue,
633
    strokeWidth: strokeWidth,
634 635
  );

636 637
  final double arrowheadScale;

638 639
  void paintArrowhead(Canvas canvas, Size size) {
    // ux, uy: a unit vector whose direction parallels the base of the arrowhead.
Ian Hickson's avatar
Ian Hickson committed
640
    // (So ux, -uy points in the direction the arrowhead points.)
641 642 643 644 645 646
    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;
647 648 649 650 651
    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;
652

653
    final Path path = Path()
654 655
      ..moveTo(radius + ux * innerRadius, radius + uy * innerRadius)
      ..lineTo(radius + ux * outerRadius, radius + uy * outerRadius)
656
      ..lineTo(arrowheadPointX, arrowheadPointY)
657
      ..close();
658
    final Paint paint = Paint()
659 660 661 662 663 664 665 666 667
      ..color = valueColor
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.fill;
    canvas.drawPath(path, paint);
  }

  @override
  void paint(Canvas canvas, Size size) {
    super.paint(canvas, size);
668 669
    if (arrowheadScale > 0.0)
      paintArrowhead(canvas, size);
670 671 672
  }
}

673 674 675
/// An indicator for the progress of refreshing the contents of a widget.
///
/// Typically used for swipe-to-refresh interactions. See [RefreshIndicator] for
Adam Barth's avatar
Adam Barth committed
676
/// a complete implementation of swipe-to-refresh driven by a [Scrollable]
677 678
/// widget.
///
679 680 681
/// The indicator arc is displayed with [valueColor], an animated value. To
/// specify a constant color use: `AlwaysStoppedAnimation<Color>(color)`.
///
682 683
/// See also:
///
684 685
///  * [RefreshIndicator], which automatically displays a [CircularProgressIndicator]
///    when the underlying vertical scrollable is overscrolled.
686
class RefreshProgressIndicator extends CircularProgressIndicator {
687 688 689
  /// Creates a refresh progress indicator.
  ///
  /// Rather than creating a refresh progress indicator directly, consider using
Adam Barth's avatar
Adam Barth committed
690
  /// a [RefreshIndicator] together with a [Scrollable] widget.
691
  ///
692
  /// {@macro flutter.material.progressIndicator.parameters}
693
  const RefreshProgressIndicator({
694 695 696 697
    Key? key,
    double? value,
    Color? backgroundColor,
    Animation<Color?>? valueColor,
698
    double strokeWidth = 2.0, // Different default than CircularProgressIndicator.
699 700
    String? semanticsLabel,
    String? semanticsValue,
701 702 703 704
  }) : super(
    key: key,
    value: value,
    backgroundColor: backgroundColor,
705 706
    valueColor: valueColor,
    strokeWidth: strokeWidth,
707 708
    semanticsLabel: semanticsLabel,
    semanticsValue: semanticsValue,
709
  );
710 711

  @override
712
  _RefreshProgressIndicatorState createState() => _RefreshProgressIndicatorState();
713 714 715
}

class _RefreshProgressIndicatorState extends _CircularProgressIndicatorState {
716
  static const double _indicatorSize = 40.0;
717

718 719 720 721 722 723
  // 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) {
724
    if (widget.value != null)
725
      _controller.value = widget.value! * (1333 / 2 / _kIndeterminateCircularDuration);
726 727
    else if (!_controller.isAnimating)
      _controller.repeat();
728 729 730
    return _buildAnimation();
  }

731
  @override
732
  Widget _buildMaterialIndicator(BuildContext context, double headValue, double tailValue, double offsetValue, double rotationValue) {
733
    final double arrowheadScale = widget.value == null ? 0.0 : (widget.value! * 2.0).clamp(0.0, 1.0);
734 735 736 737 738 739 740 741
    return widget._buildSemanticsWrapper(
      context: context,
      child: Container(
        width: _indicatorSize,
        height: _indicatorSize,
        margin: const EdgeInsets.all(4.0), // accommodate the shadow
        child: Material(
          type: MaterialType.circle,
742
          color: widget.backgroundColor ?? Theme.of(context)!.canvasColor,
743 744 745 746 747 748 749 750 751
          elevation: 2.0,
          child: Padding(
            padding: const EdgeInsets.all(12.0),
            child: CustomPaint(
              painter: _RefreshProgressIndicatorPainter(
                valueColor: widget._getValueColor(context),
                value: null, // Draw the indeterminate progress indicator.
                headValue: headValue,
                tailValue: tailValue,
752
                offsetValue: offsetValue,
753 754 755 756
                rotationValue: rotationValue,
                strokeWidth: widget.strokeWidth,
                arrowheadScale: arrowheadScale,
              ),
757 758 759 760
            ),
          ),
        ),
      ),
761 762 763
    );
  }
}