settle method

Future<void> settle({
  1. required Duration timeout,
})

Implementation

Future<void> settle({required Duration timeout}) async {
  final timeoutClock = tester.binding.clock.stopwatch()..start();
  var idleTurns = 0;
  var graceFrameApplied = false;

  await _pump();
  // The initial pump flushes callbacks queued by the preceding operation.
  // If it leaves neither external work nor a transient Flutter callback,
  // another grace frame cannot reveal useful state and only adds latency to
  // every already-idle action and screenshot boundary.
  if (!hasExternalWork() && tester.binding.transientCallbackCount == 0) {
    return;
  }
  while (timeoutClock.elapsed < timeout) {
    final hasFrameWork = tester.binding.transientCallbackCount > 0;
    if (!hasExternalWork() && !hasFrameWork) {
      if (!graceFrameApplied) {
        graceFrameApplied = true;
        final remaining = timeout - timeoutClock.elapsed;
        if (remaining <= Duration.zero) break;
        await _pump(_boundedDuration(graceFrameDuration, remaining));
        idleTurns = 0;
        continue;
      }
      await _pump();
      if (!hasExternalWork() && tester.binding.transientCallbackCount == 0) {
        idleTurns++;
        if (idleTurns >= 2) return;
      } else {
        idleTurns = 0;
      }
      continue;
    }

    idleTurns = 0;
    if (hasExternalWork()) {
      // Advance one guarded frame before awaiting an external completion
      // signal. Live bindings may only deliver that completion from work
      // scheduled by a frame, so awaiting first can deadlock the wait.
      var remaining = timeout - timeoutClock.elapsed;
      if (remaining <= Duration.zero) break;
      await _pump(_boundedDuration(graceFrameDuration, remaining));
      if (!hasExternalWork()) continue;
      remaining = timeout - timeoutClock.elapsed;
      if (remaining <= Duration.zero) break;
      // Let the owner signal completion before advancing another full
      // active frame. This avoids adding an arbitrary 100 ms to every
      // settle while still retaining a bounded pump when the signal is
      // unavailable or misbehaves.
      final completed = await _waitForExternalWorkBounded(
        timeout: _boundedDuration(
          externalWorkPollTimeout,
          remaining,
        ),
      );
      if (completed) {
        remaining = timeout - timeoutClock.elapsed;
        if (remaining <= Duration.zero) break;
        await _pump(_boundedDuration(graceFrameDuration, remaining));
        continue;
      }
    }
    final remaining = timeout - timeoutClock.elapsed;
    if (remaining <= Duration.zero) break;
    await _pump(_boundedDuration(activeFrameDuration, remaining));
  }
  throw FlutterError('settle until idle timed out');
}