文章目录
  1. 1. 常见问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int countValue = 10;
Timer _timer;

void startTimer() {
final Duration duration = Duration(seconds: 1);
cancelTimer();

_timer = Timer.periodic(duration, (timer) {
countValue = countValue - 1;
if (this.mounted) {
setState((){
//..
});
}
print(countValue);
if (countValue <= 0) {
cancelTimer();
}
});
}

常见问题

  1. Widget销毁时取消Timer

    1
    2
    3
    4
    5
    @override
    void dispose() {
    cancelTimer();
    super.dispose();
    }
  2. 生命周期变动

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    @override
    void didChangeAppLifecycleState(AppLifecycleState 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);
    }
文章目录
  1. 1. 常见问题