Flutter页面切换时如何通过dispose禁用定时器?
问题解决:页面切换时取消Flutter定时器
核心问题分析
- 未保存Timer实例,导致无法在页面销毁时取消定时器
- dispose方法中错误调用
startTimeout(),反而重复启动定时器,完全违背预期
修改后的完整代码
class _OutfitsMasterNewWidgetState extends State<OutfitsMasterNewWidget> { late FocusNode _searchFocus; late TextEditingController _searchController; final String? errorText = ''; final interval = const Duration(seconds: 1); int currentSeconds = 0; Timer? _timer; // 新增:保存定时器实例 String setStatus(int time) { if (time == 0) { return '0'; } else { int timerMaxSeconds = time; if (timerMaxSeconds - currentSeconds <= 0) { _timer?.cancel(); // 倒计时结束自动取消定时器 _timer = null; return '0'; } else { return '${((timerMaxSeconds - currentSeconds) ~/ 60).toString().padLeft(2, '0')}: ' '${((timerMaxSeconds - currentSeconds) % 60).toString().padLeft(2, '0')}'; } } } void startTimeout() { var duration = interval; _timer = Timer.periodic(duration, (timer) { setState(() { currentSeconds = timer.tick; }); // 可选:如果总秒数从widget传入,可在此判断取消 // int totalSeconds = widget.totalSeconds; // if (currentSeconds >= totalSeconds) { // timer.cancel(); // _timer = null; // } }); } @override void initState() { _searchFocus = FocusNode(); _searchController = TextEditingController(); super.initState(); startTimeout(); BlocProvider.of<OutfitsNewBloc>(context).add( OutfitsNewInitialEvent( startInitial: true, ), ); } @override void dispose() { _searchFocus.dispose(); _searchController.dispose(); _timer?.cancel(); // 页面销毁时强制取消定时器 _timer = null; // 清空引用 super.dispose(); } }
关键修改点
- 新增
Timer? _timer变量存储定时器实例,方便后续取消操作 - 修改
startTimeout(),将创建的Timer赋值给_timer - 在
dispose()方法中调用_timer?.cancel(),确保页面销毁时定时器停止运行 - 在倒计时结束的逻辑里也添加定时器取消,避免不必要的资源占用
内容的提问来源于stack exchange,提问作者Andrii Havrylyak
相关产品推荐
相关产品推荐

