waitFor method
Waits for an externally observable condition while advancing only bounded event-driven frames. This is used for startup targets whose availability is the synchronization contract, rather than waiting for an arbitrary number of fixed-duration pumps.
Implementation
Future<void> waitFor({
required bool Function() condition,
required Duration timeout,
}) async {
// Conditions are often satisfied by the preceding action or event
// callback. Avoid advancing a frame when no synchronization is needed.
if (condition()) return;
// Use the binding clock so time spent awaiting external work counts
// against the same timeout as frame advancement. Counting only requested
// pump durations let the external-work poll and following frame each
// consume time, nearly doubling waits while a live call remained pending.
final timeoutClock = tester.binding.clock.stopwatch()..start();
await _pump();
while (timeoutClock.elapsed < timeout) {
if (condition()) return;
final hasFrameWork = tester.binding.transientCallbackCount > 0;
final hasExternalWork = this.hasExternalWork();
if (hasExternalWork) {
final remaining = timeout - timeoutClock.elapsed;
await _pump(_boundedDuration(graceFrameDuration, remaining));
if (!this.hasExternalWork()) {
if (condition()) return;
continue;
}
if (timeoutClock.elapsed <= timeout && condition()) return;
final remainingAfterPump = timeout - timeoutClock.elapsed;
if (remainingAfterPump <= Duration.zero) break;
final completed = await _waitForExternalWorkBounded(
timeout: _boundedDuration(
externalWorkPollTimeout,
remainingAfterPump,
),
);
if (completed) {
await _pump();
} else {
final remainingAfterWait = timeout - timeoutClock.elapsed;
if (remainingAfterWait <= Duration.zero) break;
await _pump(
_boundedDuration(activeFrameDuration, remainingAfterWait),
);
}
if (timeoutClock.elapsed <= timeout && condition()) return;
continue;
}
final remaining = timeout - timeoutClock.elapsed;
final frameDuration =
hasFrameWork ? activeFrameDuration : graceFrameDuration;
await _pump(_boundedDuration(frameDuration, remaining));
if (condition()) return;
}
throw FlutterError('wait for condition timed out');
}