usePeriodicRerender function

int usePeriodicRerender(
  1. Duration duration, {
  2. bool isEnabled = true,
})

Periodically rerenders widget by internally incrementing useState value. Note that duration value can't be changed during the lifecycle of this hook.

final key = usePeriodicRerender(const Duration(seconds: 1), isEnabled: true);
print(key); // 0
wait(const Duration(seconds: 1));
print(key); // 1

Implementation

int usePeriodicRerender(Duration duration, {bool isEnabled = true}) {
  final (rerender, key) = useRerender();
  useEffect(() {
    if (!isEnabled) {
      return null;
    }
    final timer = Timer.periodic(duration, (timer) {
      rerender();
    });
    return () => timer.cancel();
  }, [isEnabled]);

  return key;
}