代码内容并不重要。当我想离开此页面时,只有一个问题计时器无法处理。当我离开这个页面时,sendMessage("message");
函数继续运行。有没有办法处理这个计时器?
Timer timer;
@override
void initState() {
super.initState();
timer = Timer.periodic(new Duration(seconds: 5), (timer) async {
setState(() {
unicode++;
unicodeString = unicode.toString();
if (unicodeString.length < 6) {
int different = 6 - unicodeString.length;
for (var i = 0; i < different; i++) {
unicodeString = "0" + unicodeString;
}
}
sendMessage("meesage");
showSnackBarWithKey("Message Sended !");
});
});
}
@override
void dispose() {
timer.cancel();
super.dispose();
}
错误如下。EXCEPTION CAUGHT BY WIDGETS LIBRARY The following assertion was thrown while finalizing the widget tree: 'package:flutter/src/widgets/framework.dart': Failed assertion: line 4182 pos 12: '_debugLifecycleState != _ElementLifecycle.defunct': is not true. Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause. In either case, please report this assertion by filing a bug on GitHub:
我使用处置定时器,但它不能处置定时器。我无法解决这个问题。请帮助。
最佳答案
我在运行你的代码后发现问题,
主要问题是,
当小部件从父树中完全移除时,它会在小部件上调用。
所以当你路由新页面时,
屏幕。因此(旧屏幕的)树没有被完全破坏
因此不调用 dispose 。
叫。
小部件树。所以处置被调用。
对于代码,
试试这个。
(主要部分是 pushReplacement 我用它来导航)
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => SplashScreen()));
最终代码是, class TimerButton extends StatefulWidget {
@override
_TimerButtonState createState() => _TimerButtonState();
}
class _TimerButtonState extends State<TimerButton> {
Timer _timer;
@override
void initState() {
super.initState();
_timer = Timer.periodic(new Duration(seconds: 5), (timer) async{
setState(() {
/* unicode++;
unicodeString = unicode.toString();
if (unicodeString.length < 6) {
int different = 6 - unicodeString.length;
for (var i = 0; i < different; i++) {
unicodeString = "0" + unicodeString;
}
}*/
sendMessage("meesage");
showSnackBarWithKey("Message Sended !");
});
});
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return RaisedButton(
onPressed: (){
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => SplashScreen()));
},
child: Text("data"),
);
}
}
关于flutter - 周期性定时器不能处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65222986/