refresh.dart 25 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
Ian Hickson's avatar
Ian Hickson committed
4

5 6 7 8 9 10
import 'dart:math';

import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
11

12
import 'activity_indicator.dart';
13 14 15

const double _kActivityIndicatorRadius = 14.0;
const double _kActivityIndicatorMargin = 16.0;
16

17 18
class _CupertinoSliverRefresh extends SingleChildRenderObjectWidget {
  const _CupertinoSliverRefresh({
19
    Key? key,
20 21
    this.refreshIndicatorLayoutExtent = 0.0,
    this.hasLayoutExtent = false,
22
    Widget? child,
23 24 25
  }) : assert(refreshIndicatorLayoutExtent != null),
       assert(refreshIndicatorLayoutExtent >= 0.0),
       assert(hasLayoutExtent != null),
26
       super(key: key, child: child);
27 28 29 30

  // The amount of space the indicator should occupy in the sliver in a
  // resting state when in the refreshing mode.
  final double refreshIndicatorLayoutExtent;
31

32 33
  // _RenderCupertinoSliverRefresh will paint the child in the available
  // space either way but this instructs the _RenderCupertinoSliverRefresh
34 35 36 37
  // on whether to also occupy any layoutExtent space or not.
  final bool hasLayoutExtent;

  @override
38
  _RenderCupertinoSliverRefresh createRenderObject(BuildContext context) {
39
    return _RenderCupertinoSliverRefresh(
40 41 42 43 44 45
      refreshIndicatorExtent: refreshIndicatorLayoutExtent,
      hasLayoutExtent: hasLayoutExtent,
    );
  }

  @override
46
  void updateRenderObject(BuildContext context, covariant _RenderCupertinoSliverRefresh renderObject) {
47 48 49 50 51 52 53 54 55 56 57 58
    renderObject
      ..refreshIndicatorLayoutExtent = refreshIndicatorLayoutExtent
      ..hasLayoutExtent = hasLayoutExtent;
  }
}

// RenderSliver object that gives its child RenderBox object space to paint
// in the overscrolled gap and may or may not hold that overscrolled gap
// around the RenderBox depending on whether [layoutExtent] is set.
//
// The [layoutExtentOffsetCompensation] field keeps internal accounting to
// prevent scroll position jumps as the [layoutExtent] is set and unset.
59
class _RenderCupertinoSliverRefresh extends RenderSliver
60
    with RenderObjectWithChildMixin<RenderBox> {
61
  _RenderCupertinoSliverRefresh({
62 63 64
    required double refreshIndicatorExtent,
    required bool hasLayoutExtent,
    RenderBox? child,
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
  }) : assert(refreshIndicatorExtent != null),
       assert(refreshIndicatorExtent >= 0.0),
       assert(hasLayoutExtent != null),
       _refreshIndicatorExtent = refreshIndicatorExtent,
       _hasLayoutExtent = hasLayoutExtent {
    this.child = child;
  }

  // The amount of layout space the indicator should occupy in the sliver in a
  // resting state when in the refreshing mode.
  double get refreshIndicatorLayoutExtent => _refreshIndicatorExtent;
  double _refreshIndicatorExtent;
  set refreshIndicatorLayoutExtent(double value) {
    assert(value != null);
    assert(value >= 0.0);
    if (value == _refreshIndicatorExtent)
      return;
    _refreshIndicatorExtent = value;
    markNeedsLayout();
  }

  // The child box will be laid out and painted in the available space either
87 88
  // way but this determines whether to also occupy any
  // [SliverGeometry.layoutExtent] space or not.
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  bool get hasLayoutExtent => _hasLayoutExtent;
  bool _hasLayoutExtent;
  set hasLayoutExtent(bool value) {
    assert(value != null);
    if (value == _hasLayoutExtent)
      return;
    _hasLayoutExtent = value;
    markNeedsLayout();
  }

  // This keeps track of the previously applied scroll offsets to the scrollable
  // so that when [refreshIndicatorLayoutExtent] or [hasLayoutExtent] changes,
  // the appropriate delta can be applied to keep everything in the same place
  // visually.
  double layoutExtentOffsetCompensation = 0.0;

  @override
  void performLayout() {
107
    final SliverConstraints constraints = this.constraints;
108 109 110 111 112 113 114 115 116 117 118
    // Only pulling to refresh from the top is currently supported.
    assert(constraints.axisDirection == AxisDirection.down);
    assert(constraints.growthDirection == GrowthDirection.forward);

    // The new layout extent this sliver should now have.
    final double layoutExtent =
        (_hasLayoutExtent ? 1.0 : 0.0) * _refreshIndicatorExtent;
    // If the new layoutExtent instructive changed, the SliverGeometry's
    // layoutExtent will take that value (on the next performLayout run). Shift
    // the scroll offset first so it doesn't make the scroll position suddenly jump.
    if (layoutExtent != layoutExtentOffsetCompensation) {
119
      geometry = SliverGeometry(
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
        scrollOffsetCorrection: layoutExtent - layoutExtentOffsetCompensation,
      );
      layoutExtentOffsetCompensation = layoutExtent;
      // Return so we don't have to do temporary accounting and adjusting the
      // child's constraints accounting for this one transient frame using a
      // combination of existing layout extent, new layout extent change and
      // the overlap.
      return;
    }

    final bool active = constraints.overlap < 0.0 || layoutExtent > 0.0;
    final double overscrolledExtent =
        constraints.overlap < 0.0 ? constraints.overlap.abs() : 0.0;
    // Layout the child giving it the space of the currently dragged overscroll
    // which may or may not include a sliver layout extent space that it will
    // keep after the user lets go during the refresh process.
136
    child!.layout(
137 138 139 140 141 142 143 144 145
      constraints.asBoxConstraints(
        maxExtent: layoutExtent
            // Plus only the overscrolled portion immediately preceding this
            // sliver.
            + overscrolledExtent,
      ),
      parentUsesSize: true,
    );
    if (active) {
146
      geometry = SliverGeometry(
147 148 149 150 151 152 153
        scrollExtent: layoutExtent,
        paintOrigin: -overscrolledExtent - constraints.scrollOffset,
        paintExtent: max(
          // Check child size (which can come from overscroll) because
          // layoutExtent may be zero. Check layoutExtent also since even
          // with a layoutExtent, the indicator builder may decide to not
          // build anything.
154
          max(child!.size.height, layoutExtent) - constraints.scrollOffset,
155 156 157
          0.0,
        ),
        maxPaintExtent: max(
158
          max(child!.size.height, layoutExtent) - constraints.scrollOffset,
159 160 161 162 163 164 165 166 167 168 169 170 171
          0.0,
        ),
        layoutExtent: max(layoutExtent - constraints.scrollOffset, 0.0),
      );
    } else {
      // If we never started overscrolling, return no geometry.
      geometry = SliverGeometry.zero;
    }
  }

  @override
  void paint(PaintingContext paintContext, Offset offset) {
    if (constraints.overlap < 0.0 ||
172 173
        constraints.scrollOffset + child!.size.height > 0) {
      paintContext.paintChild(child!, offset);
174 175 176 177 178 179
    }
  }

  // Nothing special done here because this sliver always paints its child
  // exactly between paintOrigin and paintExtent.
  @override
180
  void applyPaintTransform(RenderObject child, Matrix4 transform) { }
181 182 183 184 185 186 187 188 189 190
}

/// The current state of the refresh control.
///
/// Passed into the [RefreshControlIndicatorBuilder] builder function so
/// users can show different UI in different modes.
enum RefreshIndicatorMode {
  /// Initial state, when not being overscrolled into, or after the overscroll
  /// is canceled or after done and the sliver retracted away.
  inactive,
191

192 193
  /// While being overscrolled but not far enough yet to trigger the refresh.
  drag,
194

195 196 197
  /// Dragged far enough that the onRefresh callback will run and the dragged
  /// displacement is not yet at the final refresh resting state.
  armed,
198

199 200
  /// While the onRefresh task is running.
  refresh,
201

202 203 204 205 206 207 208 209 210
  /// While the indicator is animating away after refreshing.
  done,
}

/// Signature for a builder that can create a different widget to show in the
/// refresh indicator space depending on the current state of the refresh
/// control and the space available.
///
/// The `refreshTriggerPullDistance` and `refreshIndicatorExtent` parameters are
211
/// the same values passed into the [CupertinoSliverRefreshControl].
212 213 214
///
/// The `pulledExtent` parameter is the currently available space either from
/// overscrolling or as held by the sliver during refresh.
215
typedef RefreshControlIndicatorBuilder = Widget Function(
216 217 218 219 220 221 222
  BuildContext context,
  RefreshIndicatorMode refreshState,
  double pulledExtent,
  double refreshTriggerPullDistance,
  double refreshIndicatorExtent,
);

223
/// A callback function that's invoked when the [CupertinoSliverRefreshControl] is
224
/// pulled a `refreshTriggerPullDistance`. Must return a [Future]. Upon
225
/// completion of the [Future], the [CupertinoSliverRefreshControl] enters the
226
/// [RefreshIndicatorMode.done] state and will start to go away.
227
typedef RefreshCallback = Future<void> Function();
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

/// A sliver widget implementing the iOS-style pull to refresh content control.
///
/// When inserted as the first sliver in a scroll view or behind other slivers
/// that still lets the scrollable overscroll in front of this sliver (such as
/// the [CupertinoSliverNavigationBar], this widget will:
///
///  * Let the user draw inside the overscrolled area via the passed in [builder].
///  * Trigger the provided [onRefresh] function when overscrolled far enough to
///    pass [refreshTriggerPullDistance].
///  * Continue to hold [refreshIndicatorExtent] amount of space for the [builder]
///    to keep drawing inside of as the [Future] returned by [onRefresh] processes.
///  * Scroll away once the [onRefresh] [Future] completes.
///
/// The [builder] function will be informed of the current [RefreshIndicatorMode]
/// when invoking it, except in the [RefreshIndicatorMode.inactive] state when
/// no space is available and nothing needs to be built. The [builder] function
/// will otherwise be continuously invoked as the amount of space available
/// changes from overscroll, as the sliver scrolls away after the [onRefresh]
/// task is done, etc.
///
/// Only one refresh can be triggered until the previous refresh has completed
/// and the indicator sliver has retracted at least 90% of the way back.
///
252
/// Can only be used in downward-scrolling vertical lists that overscrolls. In
253 254 255 256 257 258 259 260 261 262 263
/// other words, refreshes can't be triggered with [Scrollable]s using
/// [ClampingScrollPhysics] which is the default on Android. To allow overscroll
/// on Android, use an overscrolling physics such as [BouncingScrollPhysics].
/// This can be done via:
///
///  * Providing a [BouncingScrollPhysics] (possibly in combination with a
///    [AlwaysScrollableScrollPhysics]) while constructing the scrollable.
///  * By inserting a [ScrollConfiguration] with [BouncingScrollPhysics] above
///    the scrollable.
///  * By using [CupertinoApp], which always uses a [ScrollConfiguration]
///    with [BouncingScrollPhysics] regardless of platform.
264
///
265 266 267 268
/// In a typical application, this sliver should be inserted between the app bar
/// sliver such as [CupertinoSliverNavigationBar] and your main scrollable
/// content's sliver.
///
269
/// {@tool dartpad --template=stateful_widget_cupertino}
270 271
///
/// When the user scrolls past [refreshTriggerPullDistance],
272
/// this sample shows the default iOS pull to refresh indicator for 1 second and
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
/// adds a new item to the top of the list view.
///
/// ```dart
/// List<Color> colors = [
///   CupertinoColors.systemYellow,
///   CupertinoColors.systemOrange,
///   CupertinoColors.systemPink
/// ];
/// List<Widget> items = [
///   Container(color: CupertinoColors.systemPink, height: 100.0),
///   Container(color: CupertinoColors.systemOrange, height: 100.0),
///   Container(color: CupertinoColors.systemYellow, height: 100.0),
/// ];
///
/// @override
/// Widget build(BuildContext context) {
///   return CupertinoApp(
///     home: CupertinoPageScaffold(
///       child: CustomScrollView(
///         physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
///         slivers: <Widget>[
///           const CupertinoSliverNavigationBar(largeTitle: Text('Scroll down')),
///           CupertinoSliverRefreshControl(
///             refreshTriggerPullDistance: 100.0,
///             refreshIndicatorExtent: 60.0,
///             onRefresh: () async {
///               await Future.delayed(Duration(milliseconds: 1000));
///               setState(() {
///                 items.insert(0, Container(color: colors[items.length % 3], height: 100.0));
///               });
///             },
///           ),
///           SliverList(
///             delegate: SliverChildBuilderDelegate(
///               (BuildContext context, int index) => items[index],
///               childCount: items.length,
///             ),
///           ),
///         ],
///       )
///     )
///   );
/// }
/// ```
/// {@end-tool}
///
319 320 321 322 323 324 325 326
/// See also:
///
///  * [CustomScrollView], a typical sliver holding scroll view this control
///    should go into.
///  * <https://developer.apple.com/ios/human-interface-guidelines/controls/refresh-content-controls/>
///  * [RefreshIndicator], a Material Design version of the pull-to-refresh
///    paradigm. This widget works differently than [RefreshIndicator] because
///    instead of being an overlay on top of the scrollable, the
327
///    [CupertinoSliverRefreshControl] is part of the scrollable and actively occupies
328
///    scrollable space.
329 330
class CupertinoSliverRefreshControl extends StatefulWidget {
  /// Create a new refresh control for inserting into a list of slivers.
331
  ///
332
  /// The [refreshTriggerPullDistance] and [refreshIndicatorExtent] arguments
333
  /// must not be null and must be >= 0.
334
  ///
335 336 337
  /// The [builder] argument may be null, in which case no indicator UI will be
  /// shown but the [onRefresh] will still be invoked. By default, [builder]
  /// shows a [CupertinoActivityIndicator].
338
  ///
339 340 341
  /// The [onRefresh] argument will be called when pulled far enough to trigger
  /// a refresh.
  const CupertinoSliverRefreshControl({
342
    Key? key,
343 344
    this.refreshTriggerPullDistance = _defaultRefreshTriggerPullDistance,
    this.refreshIndicatorExtent = _defaultRefreshIndicatorExtent,
345
    this.builder = buildRefreshIndicator,
346 347 348 349 350 351 352 353 354
    this.onRefresh,
  }) : assert(refreshTriggerPullDistance != null),
       assert(refreshTriggerPullDistance > 0.0),
       assert(refreshIndicatorExtent != null),
       assert(refreshIndicatorExtent >= 0.0),
       assert(
         refreshTriggerPullDistance >= refreshIndicatorExtent,
         'The refresh indicator cannot take more space in its final state '
         'than the amount initially created by overscrolling.'
355 356
       ),
       super(key: key);
357 358 359

  /// The amount of overscroll the scrollable must be dragged to trigger a reload.
  ///
360 361
  /// Must not be null, must be larger than 0.0 and larger than
  /// [refreshIndicatorExtent]. Defaults to 100px when not specified.
362 363 364 365 366 367 368 369 370 371
  ///
  /// When overscrolled past this distance, [onRefresh] will be called if not
  /// null and the [builder] will build in the [RefreshIndicatorMode.armed] state.
  final double refreshTriggerPullDistance;

  /// The amount of space the refresh indicator sliver will keep holding while
  /// [onRefresh]'s [Future] is still running.
  ///
  /// Must not be null and must be positive, but can be 0.0, in which case the
  /// sliver will start retracting back to 0.0 as soon as the refresh is started.
372
  /// Defaults to 60px when not specified.
373 374 375 376 377 378 379 380 381 382 383 384 385
  ///
  /// Must be smaller than [refreshTriggerPullDistance], since the sliver
  /// shouldn't grow further after triggering the refresh.
  final double refreshIndicatorExtent;

  /// A builder that's called as this sliver's size changes, and as the state
  /// changes.
  ///
  /// Can be set to null, in which case nothing will be drawn in the overscrolled
  /// space.
  ///
  /// Will not be called when the available space is zero such as before any
  /// overscroll.
386
  final RefreshControlIndicatorBuilder? builder;
387 388 389 390 391 392 393 394 395

  /// Callback invoked when pulled by [refreshTriggerPullDistance].
  ///
  /// If provided, must return a [Future] which will keep the indicator in the
  /// [RefreshIndicatorMode.refresh] state until the [Future] completes.
  ///
  /// Can be null, in which case a single frame of [RefreshIndicatorMode.armed]
  /// state will be drawn before going immediately to the [RefreshIndicatorMode.done]
  /// where the sliver will start retracting.
396
  final RefreshCallback? onRefresh;
397

398 399
  static const double _defaultRefreshTriggerPullDistance = 100.0;
  static const double _defaultRefreshIndicatorExtent = 60.0;
400

401
  /// Retrieve the current state of the CupertinoSliverRefreshControl. The same as the
402 403 404
  /// state that gets passed into the [builder] function. Used for testing.
  @visibleForTesting
  static RefreshIndicatorMode state(BuildContext context) {
405
    final _CupertinoSliverRefreshControlState state = context.findAncestorStateOfType<_CupertinoSliverRefreshControlState>()!;
406 407 408
    return state.refreshState;
  }

409 410 411 412 413 414 415 416
  /// Builds a refresh indicator that reflects the standard iOS pull-to-refresh
  /// behavior. Specifically, this entails presenting an activity indicator that
  /// changes depending on the current refreshState. As the user initially drags
  /// down, the indicator will gradually reveal individual ticks until the refresh
  /// becomes armed. At this point, the animated activity indicator will begin rotating.
  /// Once the refresh has completed, the activity indicator shrinks away as the
  /// space allocation animates back to closed.
  static Widget buildRefreshIndicator(
417
    BuildContext context,
418 419 420 421 422
    RefreshIndicatorMode refreshState,
    double pulledExtent,
    double refreshTriggerPullDistance,
    double refreshIndicatorExtent,
  ) {
423 424 425 426 427 428 429 430 431 432 433
    final double percentageComplete = pulledExtent / refreshTriggerPullDistance;

    // Place the indicator at the top of the sliver that opens up. Note that we're using
    // a Stack/Positioned widget because the CupertinoActivityIndicator does some internal
    // translations based on the current size (which grows as the user drags) that makes
    // Padding calculations difficult. Rather than be reliant on the internal implementation
    // of the activity indicator, the Positioned widget allows us to be explicit where the
    // widget gets placed. Also note that the indicator should appear over the top of the
    // dragged widget, hence the use of Overflow.visible.
    return Center(
      child: Stack(
434
        clipBehavior: Clip.none,
435 436 437 438 439 440 441 442
        children: <Widget>[
          Positioned(
            top: _kActivityIndicatorMargin,
            left: 0.0,
            right: 0.0,
            child: _buildIndicatorForRefreshState(refreshState, _kActivityIndicatorRadius, percentageComplete),
          ),
        ],
443 444 445 446
      ),
    );
  }

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
  static Widget _buildIndicatorForRefreshState(RefreshIndicatorMode refreshState, double radius, double percentageComplete) {
    switch (refreshState) {
      case RefreshIndicatorMode.drag:
        // While we're dragging, we draw individual ticks of the spinner while simultaneously
        // easing the opacity in. Note that the opacity curve values here were derived using
        // Xcode through inspecting a native app running on iOS 13.5.
        const Curve opacityCurve = Interval(0.0, 0.35, curve: Curves.easeInOut);
        return Opacity(
          opacity: opacityCurve.transform(percentageComplete),
          child: CupertinoActivityIndicator.partiallyRevealed(radius: radius, progress: percentageComplete),
        );
      case RefreshIndicatorMode.armed:
      case RefreshIndicatorMode.refresh:
        // Once we're armed or performing the refresh, we just show the normal spinner.
        return CupertinoActivityIndicator(radius: radius);
      case RefreshIndicatorMode.done:
        // When the user lets go, the standard transition is to shrink the spinner.
        return CupertinoActivityIndicator(radius: radius * percentageComplete);
465
      case RefreshIndicatorMode.inactive:
466 467 468 469 470
        // Anything else doesn't show anything.
        return Container();
    }
  }

471
  @override
472
  _CupertinoSliverRefreshControlState createState() => _CupertinoSliverRefreshControlState();
473 474
}

475
class _CupertinoSliverRefreshControlState extends State<CupertinoSliverRefreshControl> {
476 477
  // Reset the state from done to inactive when only this fraction of the
  // original `refreshTriggerPullDistance` is left.
478
  static const double _inactiveResetOverscrollFraction = 0.1;
479

480
  late RefreshIndicatorMode refreshState;
481
  // [Future] returned by the widget's `onRefresh`.
482
  Future<void>? refreshTask;
483 484 485
  // The amount of space available from the inner indicator box's perspective.
  //
  // The value is the sum of the sliver's layout extent and the overscroll
486
  // (which partially gets transferred into the layout extent when the refresh
487 488
  // triggers).
  //
489
  // The value of latestIndicatorBoxExtent doesn't change when the sliver scrolls
490
  // away without retracting; it is independent from the sliver's scrollOffset.
491
  double latestIndicatorBoxExtent = 0.0;
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
  bool hasSliverLayoutExtent = false;

  @override
  void initState() {
    super.initState();
    refreshState = RefreshIndicatorMode.inactive;
  }

  // A state machine transition calculator. Multiple states can be transitioned
  // through per single call.
  RefreshIndicatorMode transitionNextState() {
    RefreshIndicatorMode nextState;

    void goToDone() {
      nextState = RefreshIndicatorMode.done;
      // Either schedule the RenderSliver to re-layout on the next frame
      // when not currently in a frame or schedule it on the next frame.
509
      if (SchedulerBinding.instance!.schedulerPhase == SchedulerPhase.idle) {
510 511
        setState(() => hasSliverLayoutExtent = false);
      } else {
512
        SchedulerBinding.instance!.addPostFrameCallback((Duration timestamp) {
513 514 515 516 517 518 519
          setState(() => hasSliverLayoutExtent = false);
        });
      }
    }

    switch (refreshState) {
      case RefreshIndicatorMode.inactive:
520
        if (latestIndicatorBoxExtent <= 0) {
521 522 523 524 525 526 527
          return RefreshIndicatorMode.inactive;
        } else {
          nextState = RefreshIndicatorMode.drag;
        }
        continue drag;
      drag:
      case RefreshIndicatorMode.drag:
528
        if (latestIndicatorBoxExtent == 0) {
529
          return RefreshIndicatorMode.inactive;
530
        } else if (latestIndicatorBoxExtent < widget.refreshTriggerPullDistance) {
531 532 533 534 535 536 537
          return RefreshIndicatorMode.drag;
        } else {
          if (widget.onRefresh != null) {
            HapticFeedback.mediumImpact();
            // Call onRefresh after this frame finished since the function is
            // user supplied and we're always here in the middle of the sliver's
            // performLayout.
538 539
            SchedulerBinding.instance!.addPostFrameCallback((Duration timestamp) {
              refreshTask = widget.onRefresh!()..whenComplete(() {
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
                if (mounted) {
                  setState(() => refreshTask = null);
                  // Trigger one more transition because by this time, BoxConstraint's
                  // maxHeight might already be resting at 0 in which case no
                  // calls to [transitionNextState] will occur anymore and the
                  // state may be stuck in a non-inactive state.
                  refreshState = transitionNextState();
                }
              });
              setState(() => hasSliverLayoutExtent = true);
            });
          }
          return RefreshIndicatorMode.armed;
        }
      case RefreshIndicatorMode.armed:
        if (refreshState == RefreshIndicatorMode.armed && refreshTask == null) {
          goToDone();
          continue done;
        }

560
        if (latestIndicatorBoxExtent > widget.refreshIndicatorExtent) {
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
          return RefreshIndicatorMode.armed;
        } else {
          nextState = RefreshIndicatorMode.refresh;
        }
        continue refresh;
      refresh:
      case RefreshIndicatorMode.refresh:
        if (refreshTask != null) {
          return RefreshIndicatorMode.refresh;
        } else {
          goToDone();
        }
        continue done;
      done:
      case RefreshIndicatorMode.done:
        // Let the transition back to inactive trigger before strictly going
        // to 0.0 since the last bit of the animation can take some time and
        // can feel sluggish if not going all the way back to 0.0 prevented
        // a subsequent pull-to-refresh from starting.
580
        if (latestIndicatorBoxExtent >
581
            widget.refreshTriggerPullDistance * _inactiveResetOverscrollFraction) {
582 583 584 585 586 587 588 589 590 591 592 593
          return RefreshIndicatorMode.done;
        } else {
          nextState = RefreshIndicatorMode.inactive;
        }
        break;
    }

    return nextState;
  }

  @override
  Widget build(BuildContext context) {
594
    return _CupertinoSliverRefresh(
595 596 597 598
      refreshIndicatorLayoutExtent: widget.refreshIndicatorExtent,
      hasLayoutExtent: hasSliverLayoutExtent,
      // A LayoutBuilder lets the sliver's layout changes be fed back out to
      // its owner to trigger state changes.
599
      child: LayoutBuilder(
600
        builder: (BuildContext context, BoxConstraints constraints) {
601
          latestIndicatorBoxExtent = constraints.maxHeight;
602
          refreshState = transitionNextState();
603
          if (widget.builder != null && latestIndicatorBoxExtent > 0) {
604
            return widget.builder!(
605 606
              context,
              refreshState,
607
              latestIndicatorBoxExtent,
608 609 610 611
              widget.refreshTriggerPullDistance,
              widget.refreshIndicatorExtent,
            );
          }
612
          return Container();
613
        },
614
      ),
615 616 617
    );
  }
}