65 lines
1.4 KiB
Dart
65 lines
1.4 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:flutter/material.dart';
|
|
|
|
const pollInterval = Duration(seconds: 5);
|
|
|
|
/// Calls [onPoll] every five seconds while the app is resumed.
|
|
class ForegroundPoll extends StatefulWidget {
|
|
const ForegroundPoll({super.key, required this.onPoll, required this.child});
|
|
|
|
final Future<void> Function() onPoll;
|
|
final Widget child;
|
|
|
|
@override
|
|
State<ForegroundPoll> createState() => _ForegroundPollState();
|
|
}
|
|
|
|
class _ForegroundPollState extends State<ForegroundPoll>
|
|
with WidgetsBindingObserver {
|
|
Timer? _timer;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
WidgetsBinding.instance.addObserver(this);
|
|
_start();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_stop();
|
|
WidgetsBinding.instance.removeObserver(this);
|
|
super.dispose();
|
|
}
|
|
|
|
@override
|
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
|
switch (state) {
|
|
case AppLifecycleState.resumed:
|
|
_start();
|
|
unawaited(widget.onPoll());
|
|
case AppLifecycleState.paused:
|
|
case AppLifecycleState.hidden:
|
|
case AppLifecycleState.detached:
|
|
_stop();
|
|
case AppLifecycleState.inactive:
|
|
break;
|
|
}
|
|
}
|
|
|
|
void _start() {
|
|
_timer ??= Timer.periodic(pollInterval, (_) {
|
|
unawaited(widget.onPoll());
|
|
});
|
|
}
|
|
|
|
void _stop() {
|
|
_timer?.cancel();
|
|
_timer = null;
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) => widget.child;
|
|
}
|