refresh_indicator.dart 18 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 6
// @dart = 2.8

7
import 'dart:async';
8
import 'dart:math' as math;
9 10 11

import 'package:flutter/widgets.dart';

12 13
import 'debug.dart';
import 'material_localizations.dart';
14
import 'progress_indicator.dart';
15
import 'theme.dart';
16 17 18 19 20 21 22 23 24 25

// The over-scroll distance that moves the indicator to its maximum
// displacement, as a percentage of the scrollable's container extent.
const double _kDragContainerExtentPercentage = 0.25;

// How much the scroll's drag gesture can overshoot the RefreshIndicator's
// displacement; max displacement = _kDragSizeFactorLimit * displacement.
const double _kDragSizeFactorLimit = 1.5;

// When the scroll ends, the duration of the refresh indicator's animation
Josh Soref's avatar
Josh Soref committed
26
// to the RefreshIndicator's displacement.
27
const Duration _kIndicatorSnapDuration = Duration(milliseconds: 150);
28 29 30

// The duration of the ScaleTransition that starts when the refresh action
// has completed.
31
const Duration _kIndicatorScaleDuration = Duration(milliseconds: 200);
32

33 34 35 36 37
/// The signature for a function that's called when the user has dragged a
/// [RefreshIndicator] far enough to demonstrate that they want the app to
/// refresh. The returned [Future] must complete when the refresh operation is
/// finished.
///
38
/// Used by [RefreshIndicator.onRefresh].
39
typedef RefreshCallback = Future<void> Function();
40

41 42
// The state machine moves through these modes only when the scrollable
// identified by scrollableKey has been scrolled to its min or max limit.
43
enum _RefreshIndicatorMode {
44 45 46 47 48 49
  drag,     // Pointer is down.
  armed,    // Dragged far enough that an up event will run the onRefresh callback.
  snap,     // Animating to the indicator's final "displacement".
  refresh,  // Running the refresh callback.
  done,     // Animating the indicator's fade-out after refreshing.
  canceled, // Animating the indicator's fade-out after not arming.
50 51
}

52 53
/// A widget that supports the Material "swipe to refresh" idiom.
///
Adam Barth's avatar
Adam Barth committed
54
/// When the child's [Scrollable] descendant overscrolls, an animated circular
55 56 57 58 59 60
/// progress indicator is faded into view. When the scroll ends, if the
/// indicator has been dragged far enough for it to become completely opaque,
/// the [onRefresh] callback is called. The callback is expected to update the
/// scrollable's contents and then complete the [Future] it returns. The refresh
/// indicator disappears after the callback's [Future] has completed.
///
61 62 63 64 65 66 67 68 69
/// ## Troubleshooting
///
/// ### Refresh indicator does not show up
///
/// The [RefreshIndicator] will appear if its scrollable descendant can be
/// overscrolled, i.e. if the scrollable's content is bigger than its viewport.
/// To ensure that the [RefreshIndicator] will always appear, even if the
/// scrollable's content fits within its viewport, set the scrollable's
/// [Scrollable.physics] property to [AlwaysScrollableScrollPhysics]:
70 71
///
/// ```dart
72
/// ListView(
73 74
///   physics: const AlwaysScrollableScrollPhysics(),
///   children: ...
75
/// )
76 77 78
/// ```
///
/// A [RefreshIndicator] can only be used with a vertical scroll view.
79 80 81
///
/// See also:
///
82
///  * <https://material.io/design/platform-guidance/android-swipe-to-refresh.html>
83
///  * [RefreshIndicatorState], can be used to programmatically show the refresh indicator.
84 85
///  * [RefreshProgressIndicator], widget used by [RefreshIndicator] to show
///    the inner circular progress spinner during refreshes.
86
///  * [CupertinoSliverRefreshControl], an iOS equivalent of the pull-to-refresh pattern.
87 88 89
///    Must be used as a sliver inside a [CustomScrollView] instead of wrapping
///    around a [ScrollView] because it's a part of the scrollable instead of
///    being overlaid on top of it.
90
class RefreshIndicator extends StatefulWidget {
91 92
  /// Creates a refresh indicator.
  ///
93 94
  /// The [onRefresh], [child], and [notificationPredicate] arguments must be
  /// non-null. The default
95
  /// [displacement] is 40.0 logical pixels.
96 97 98 99
  ///
  /// The [semanticsLabel] is used to specify an accessibility label for this widget.
  /// If it is null, it will be defaulted to [MaterialLocalizations.refreshIndicatorSemanticLabel].
  /// An empty string may be passed to avoid having anything read by screen reading software.
100
  /// The [semanticsValue] may be used to specify progress on the widget.
101
  const RefreshIndicator({
102
    Key key,
103
    @required this.child,
104
    this.displacement = 40.0,
105
    @required this.onRefresh,
106
    this.color,
107
    this.backgroundColor,
108
    this.notificationPredicate = defaultScrollNotificationPredicate,
109 110
    this.semanticsLabel,
    this.semanticsValue,
111
    this.strokeWidth = 2.0
112 113
  }) : assert(child != null),
       assert(onRefresh != null),
114
       assert(notificationPredicate != null),
115
       assert(strokeWidth != null),
116
       super(key: key);
117

118 119
  /// The widget below this widget in the tree.
  ///
120 121
  /// The refresh indicator will be stacked on top of this child. The indicator
  /// will appear when child's Scrollable descendant is over-scrolled.
122 123
  ///
  /// Typically a [ListView] or [CustomScrollView].
124 125
  final Widget child;

126 127 128
  /// The distance from the child's top or bottom edge to where the refresh
  /// indicator will settle. During the drag that exposes the refresh indicator,
  /// its actual displacement may significantly exceed this value.
129 130 131 132
  final double displacement;

  /// A function that's called when the user has dragged the refresh indicator
  /// far enough to demonstrate that they want the app to refresh. The returned
133
  /// [Future] must complete when the refresh operation is finished.
134
  final RefreshCallback onRefresh;
135

136
  /// The progress indicator's foreground color. The current theme's
137
  /// [ThemeData.accentColor] by default.
138 139 140 141 142
  final Color color;

  /// The progress indicator's background color. The current theme's
  /// [ThemeData.canvasColor] by default.
  final Color backgroundColor;
143

144 145 146 147 148 149
  /// A check that specifies whether a [ScrollNotification] should be
  /// handled by this widget.
  ///
  /// By default, checks whether `notification.depth == 0`. Set it to something
  /// else for more complicated layouts.
  final ScrollNotificationPredicate notificationPredicate;
150

151 152 153 154 155 156 157 158 159
  /// {@macro flutter.material.progressIndicator.semanticsLabel}
  ///
  /// This will be defaulted to [MaterialLocalizations.refreshIndicatorSemanticLabel]
  /// if it is null.
  final String semanticsLabel;

  /// {@macro flutter.material.progressIndicator.semanticsValue}
  final String semanticsValue;

160 161 162 163 164
  /// Defines `strokeWidth` for `RefreshIndicator`.
  ///
  /// By default, the value of `strokeWidth` is 2.0 pixels.
  final double strokeWidth;

165
  @override
166
  RefreshIndicatorState createState() => RefreshIndicatorState();
167 168
}

169 170
/// Contains the state for a [RefreshIndicator]. This class can be used to
/// programmatically show the refresh indicator, see the [show] method.
171
class RefreshIndicatorState extends State<RefreshIndicator> with TickerProviderStateMixin<RefreshIndicator> {
172
  AnimationController _positionController;
173
  AnimationController _scaleController;
174
  Animation<double> _positionFactor;
175
  Animation<double> _scaleFactor;
176
  Animation<double> _value;
177 178
  Animation<Color> _valueColor;

179
  _RefreshIndicatorMode _mode;
180
  Future<void> _pendingRefreshFuture;
181 182
  bool _isIndicatorAtTop;
  double _dragOffset;
183

184 185 186 187
  static final Animatable<double> _threeQuarterTween = Tween<double>(begin: 0.0, end: 0.75);
  static final Animatable<double> _kDragSizeFactorLimitTween = Tween<double>(begin: 0.0, end: _kDragSizeFactorLimit);
  static final Animatable<double> _oneToZeroTween = Tween<double>(begin: 1.0, end: 0.0);

188 189 190
  @override
  void initState() {
    super.initState();
191
    _positionController = AnimationController(vsync: this);
192 193
    _positionFactor = _positionController.drive(_kDragSizeFactorLimitTween);
    _value = _positionController.drive(_threeQuarterTween); // The "value" of the circular progress indicator during a drag.
194

195
    _scaleController = AnimationController(vsync: this);
196
    _scaleFactor = _scaleController.drive(_oneToZeroTween);
197 198 199
  }

  @override
200
  void didChangeDependencies() {
201
    final ThemeData theme = Theme.of(context);
202 203 204
    _valueColor = _positionController.drive(
      ColorTween(
        begin: (widget.color ?? theme.accentColor).withOpacity(0.0),
205
        end: (widget.color ?? theme.accentColor).withOpacity(1.0),
206 207 208 209
      ).chain(CurveTween(
        curve: const Interval(0.0, 1.0 / _kDragSizeFactorLimit)
      )),
    );
210
    super.didChangeDependencies();
211 212 213 214
  }

  @override
  void dispose() {
215
    _positionController.dispose();
216 217 218 219
    _scaleController.dispose();
    super.dispose();
  }

Adam Barth's avatar
Adam Barth committed
220
  bool _handleScrollNotification(ScrollNotification notification) {
221
    if (!widget.notificationPredicate(notification))
222 223
      return false;
    if (notification is ScrollStartNotification && notification.metrics.extentBefore == 0.0 &&
224
        _mode == null && _start(notification.metrics.axisDirection)) {
225 226 227
      setState(() {
        _mode = _RefreshIndicatorMode.drag;
      });
228
      return false;
229 230
    }
    bool indicatorAtTopNow;
231
    switch (notification.metrics.axisDirection) {
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
      case AxisDirection.down:
        indicatorAtTopNow = true;
        break;
      case AxisDirection.up:
        indicatorAtTopNow = false;
        break;
      case AxisDirection.left:
      case AxisDirection.right:
        indicatorAtTopNow = null;
        break;
    }
    if (indicatorAtTopNow != _isIndicatorAtTop) {
      if (_mode == _RefreshIndicatorMode.drag || _mode == _RefreshIndicatorMode.armed)
        _dismiss(_RefreshIndicatorMode.canceled);
    } else if (notification is ScrollUpdateNotification) {
      if (_mode == _RefreshIndicatorMode.drag || _mode == _RefreshIndicatorMode.armed) {
        if (notification.metrics.extentBefore > 0.0) {
          _dismiss(_RefreshIndicatorMode.canceled);
        } else {
          _dragOffset -= notification.scrollDelta;
          _checkDragOffset(notification.metrics.viewportDimension);
        }
      }
255 256 257 258 259 260
      if (_mode == _RefreshIndicatorMode.armed && notification.dragDetails == null) {
        // On iOS start the refresh when the Scrollable bounces back from the
        // overscroll (ScrollNotification indicating this don't have dragDetails
        // because the scroll activity is not directly triggered by a drag).
        _show();
      }
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    } else if (notification is OverscrollNotification) {
      if (_mode == _RefreshIndicatorMode.drag || _mode == _RefreshIndicatorMode.armed) {
        _dragOffset -= notification.overscroll / 2.0;
        _checkDragOffset(notification.metrics.viewportDimension);
      }
    } else if (notification is ScrollEndNotification) {
      switch (_mode) {
        case _RefreshIndicatorMode.armed:
          _show();
          break;
        case _RefreshIndicatorMode.drag:
          _dismiss(_RefreshIndicatorMode.canceled);
          break;
        default:
          // do nothing
          break;
      }
278 279
    }
    return false;
280 281
  }

282 283 284 285 286 287
  bool _handleGlowNotification(OverscrollIndicatorNotification notification) {
    if (notification.depth != 0 || !notification.leading)
      return false;
    if (_mode == _RefreshIndicatorMode.drag) {
      notification.disallowGlow();
      return true;
288
    }
289
    return false;
290 291
  }

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
  bool _start(AxisDirection direction) {
    assert(_mode == null);
    assert(_isIndicatorAtTop == null);
    assert(_dragOffset == null);
    switch (direction) {
      case AxisDirection.down:
        _isIndicatorAtTop = true;
        break;
      case AxisDirection.up:
        _isIndicatorAtTop = false;
        break;
      case AxisDirection.left:
      case AxisDirection.right:
        _isIndicatorAtTop = null;
        // we do not support horizontal scroll views.
        return false;
    }
309 310
    _dragOffset = 0.0;
    _scaleController.value = 0.0;
311 312
    _positionController.value = 0.0;
    return true;
313 314
  }

315 316 317 318 319
  void _checkDragOffset(double containerExtent) {
    assert(_mode == _RefreshIndicatorMode.drag || _mode == _RefreshIndicatorMode.armed);
    double newValue = _dragOffset / (containerExtent * _kDragContainerExtentPercentage);
    if (_mode == _RefreshIndicatorMode.armed)
      newValue = math.max(newValue, 1.0 / _kDragSizeFactorLimit);
320
    _positionController.value = newValue.clamp(0.0, 1.0) as double; // this triggers various rebuilds
321 322
    if (_mode == _RefreshIndicatorMode.drag && _valueColor.value.alpha == 0xFF)
      _mode = _RefreshIndicatorMode.armed;
323 324
  }

325
  // Stop showing the refresh indicator.
326
  Future<void> _dismiss(_RefreshIndicatorMode newMode) async {
327
    await Future<void>.value();
328 329 330 331
    // This can only be called from _show() when refreshing and
    // _handleScrollNotification in response to a ScrollEndNotification or
    // direction change.
    assert(newMode == _RefreshIndicatorMode.canceled || newMode == _RefreshIndicatorMode.done);
332
    setState(() {
333
      _mode = newMode;
334
    });
335 336
    switch (_mode) {
      case _RefreshIndicatorMode.done:
337 338
        await _scaleController.animateTo(1.0, duration: _kIndicatorScaleDuration);
        break;
339 340 341 342 343
      case _RefreshIndicatorMode.canceled:
        await _positionController.animateTo(0.0, duration: _kIndicatorScaleDuration);
        break;
      default:
        assert(false);
344
    }
345 346 347
    if (mounted && _mode == newMode) {
      _dragOffset = null;
      _isIndicatorAtTop = null;
348 349 350 351
      setState(() {
        _mode = null;
      });
    }
352 353
  }

354 355 356
  void _show() {
    assert(_mode != _RefreshIndicatorMode.refresh);
    assert(_mode != _RefreshIndicatorMode.snap);
357
    final Completer<void> completer = Completer<void>();
358
    _pendingRefreshFuture = completer.future;
359
    _mode = _RefreshIndicatorMode.snap;
360
    _positionController
361
      .animateTo(1.0 / _kDragSizeFactorLimit, duration: _kIndicatorSnapDuration)
362
      .then<void>((void value) {
363
        if (mounted && _mode == _RefreshIndicatorMode.snap) {
364
          assert(widget.onRefresh != null);
365 366 367 368 369
          setState(() {
            // Show the indeterminate progress indicator.
            _mode = _RefreshIndicatorMode.refresh;
          });

370
          final Future<void> refreshResult = widget.onRefresh();
371 372
          assert(() {
            if (refreshResult == null)
373 374
              FlutterError.reportError(FlutterErrorDetails(
                exception: FlutterError(
375 376 377
                  'The onRefresh callback returned null.\n'
                  'The RefreshIndicator onRefresh callback must return a Future.'
                ),
378
                context: ErrorDescription('when calling onRefresh'),
379 380 381
                library: 'material library',
              ));
            return true;
382
          }());
383 384 385
          if (refreshResult == null)
            return;
          refreshResult.whenComplete(() {
386 387
            if (mounted && _mode == _RefreshIndicatorMode.refresh) {
              completer.complete();
388
              _dismiss(_RefreshIndicatorMode.done);
389 390 391
            }
          });
        }
392 393 394 395 396 397 398
      });
  }

  /// Show the refresh indicator and run the refresh callback as if it had
  /// been started interactively. If this method is called while the refresh
  /// callback is running, it quietly does nothing.
  ///
399
  /// Creating the [RefreshIndicator] with a [GlobalKey<RefreshIndicatorState>]
400
  /// makes it possible to refer to the [RefreshIndicatorState].
401
  ///
402 403
  /// The future returned from this method completes when the
  /// [RefreshIndicator.onRefresh] callback's future completes.
404 405 406 407 408 409 410
  ///
  /// If you await the future returned by this function from a [State], you
  /// should check that the state is still [mounted] before calling [setState].
  ///
  /// When initiated in this manner, the refresh indicator is independent of any
  /// actual scroll view. It defaults to showing the indicator at the top. To
  /// show it at the bottom, set `atTop` to false.
411
  Future<void> show({ bool atTop = true }) {
412 413
    if (_mode != _RefreshIndicatorMode.refresh &&
        _mode != _RefreshIndicatorMode.snap) {
414 415
      if (_mode == null)
        _start(atTop ? AxisDirection.down : AxisDirection.up);
416
      _show();
417
    }
418
    return _pendingRefreshFuture;
419 420
  }

421 422
  @override
  Widget build(BuildContext context) {
423
    assert(debugCheckHasMaterialLocalizations(context));
424
    final Widget child = NotificationListener<ScrollNotification>(
425
      onNotification: _handleScrollNotification,
426
      child: NotificationListener<OverscrollIndicatorNotification>(
427
        onNotification: _handleGlowNotification,
428
        child: widget.child,
429 430
      ),
    );
431 432 433 434 435 436 437 438 439 440
    assert(() {
      if (_mode == null) {
        assert(_dragOffset == null);
        assert(_isIndicatorAtTop == null);
      } else {
        assert(_dragOffset != null);
        assert(_isIndicatorAtTop != null);
      }
      return true;
    }());
441

442 443 444
    final bool showIndeterminateIndicator =
      _mode == _RefreshIndicatorMode.refresh || _mode == _RefreshIndicatorMode.done;

445
    return Stack(
446 447
      children: <Widget>[
        child,
448
        if (_mode != null) Positioned(
449 450 451 452
          top: _isIndicatorAtTop ? 0.0 : null,
          bottom: !_isIndicatorAtTop ? 0.0 : null,
          left: 0.0,
          right: 0.0,
453
          child: SizeTransition(
454
            axisAlignment: _isIndicatorAtTop ? 1.0 : -1.0,
455
            sizeFactor: _positionFactor, // this is what brings it down
456
            child: Container(
457
              padding: _isIndicatorAtTop
458 459
                ? EdgeInsets.only(top: widget.displacement)
                : EdgeInsets.only(bottom: widget.displacement),
460
              alignment: _isIndicatorAtTop
461 462
                ? Alignment.topCenter
                : Alignment.bottomCenter,
463
              child: ScaleTransition(
464
                scale: _scaleFactor,
465
                child: AnimatedBuilder(
466 467
                  animation: _positionController,
                  builder: (BuildContext context, Widget child) {
468
                    return RefreshProgressIndicator(
469 470
                      semanticsLabel: widget.semanticsLabel ?? MaterialLocalizations.of(context).refreshIndicatorSemanticLabel,
                      semanticsValue: widget.semanticsValue,
471 472
                      value: showIndeterminateIndicator ? null : _value.value,
                      valueColor: _valueColor,
473
                      backgroundColor: widget.backgroundColor,
474
                      strokeWidth: widget.strokeWidth,
475 476 477 478 479
                    );
                  },
                ),
              ),
            ),
480
          ),
481 482
        ),
      ],
483 484 485
    );
  }
}