flushTimers method Null safety

void flushTimers(
  1. {Duration timeout = const Duration(hours: 1),
  2. bool flushPeriodicTimers = true}
)

Elapses time until there are no more active timers.

If flushPeriodicTimers is true (the default), this will repeatedly run periodic timers until they're explicitly canceled. Otherwise, this will stop when the only active timers are periodic.

The timeout controls how much fake time may elapse before a StateError is thrown. This ensures that a periodic timer doesn't cause this method to deadlock. It defaults to one hour.

Implementation

void flushTimers(
    {Duration timeout = const Duration(hours: 1),
    bool flushPeriodicTimers = true}) {
  var absoluteTimeout = _elapsed + timeout;
  _fireTimersWhile((timer) {
    if (timer._nextCall > absoluteTimeout) {
      // TODO(nweiz): Make this a [TimeoutException].
      throw StateError('Exceeded timeout $timeout while flushing timers');
    }

    if (flushPeriodicTimers) return _timers.isNotEmpty;

    // Continue firing timers until the only ones left are periodic *and*
    // every periodic timer has had a change to run against the final
    // value of [_elapsed].
    return _timers
        .any((timer) => !timer.isPeriodic || timer._nextCall <= _elapsed);
  });
}