* * * * * * * * * * * * * * * * * * * * * * * * *
preface
The author recently encountered some problems in the process of using Timer when writing Flutter. I will share this in this article.
Create Timer
Create a Flutter Timer that performs 10 actions at intervals of 1 second using the following code.
int countValue = 10;
Timer _timer;
/ / start the Timer
void _startTimer() {
final Duration duration = Duration(seconds: 1);
cancelTimer();
_timer = Timer.periodic(duration, (timer) {
countValue = countValue - 1;
if (this.mounted) {
setState(() {
});
}
print('CountValue');
print(countValue);
if (countValue <= 0) { cancelTimer(); }}); }Copy the code
Ii. Common problems of Timer
While using the Flutter Timer, you may forget to cancel the Timer when the page is destroyed or the application enters the background. Below, I would like to share with you the methods of canceling Timer in corresponding scenarios.
1. Return to previous page without destroying Timer
The processing method is as follows:
1.1 Implement the Timer cancellation logic
void cancelTimer() {
if(_timer ! =null) { _timer.cancel(); }}Copy the code
1.2 When the page is destroyed, the logic to cancel the Timer is called
@override
void dispose() {
cancelTimer();
super.dispose();
}
Copy the code
2. Cancel the life cycle related to the Timer
When the application goes into the background, we also want to cancel the Timer, which is done as follows: implement the abstract class WidgetsBindingObserver interface, and implement the corresponding abstract method to cancel the Timer processing logic.
2.1 The current State class complies with the WidgetsBindingObserver protocol
class _TimerState extends State<TimerPage> with WidgetsBindingObserver {
}
Copy the code
2.2 The State class implements the following methods to detect application life cycle changes
Cancel the timer in the following method to declare the period change. Once the application is in the background, it goes to Inactive and then paused. In this case, you can cancel the timer to avoid the application still executing the timer process after entering the background.
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
print('state of the state:$state');
switch (state) {
case AppLifecycleState.resumed: {
break;
}
case AppLifecycleState.paused:{
cancelTimer();
break;
}
case AppLifecycleState.inactive:{
cancelTimer();
break;
}
case AppLifecycleState.detached:{
cancelTimer();
break; }}super.didChangeAppLifecycleState(state);
}
Copy the code
Third, refer to the learning website
Timer class
4. Recommended articles
RenderObjectElement and RenderObjectWidget of Flutter
The StatelessWidget in A Flutter and its lifecycle The Widget in a Flutter The Element in a Flutter (Part 2) B Swift 5.1 (21) – Generic Swift 5.1 (20) – Protocol Swift 5.1 (19) – Extended Swift 5.1 (18) – Nested types