我有小部件,数据定期更改,我正在使用Timer.periodic来重建小部件。这开始工作顺利,但很快变得波涛汹涌是否有更好的方法来做到这一点?
class _MainScreenState extends State<MainScreen> {
static const Duration duration = Duration(milliseconds: 16);
update(){
system.updatePos(duration.inMilliseconds/1000);
setState(() {});
}
@override
Widget build(BuildContext context) {
Timer.periodic(duration, (timer){
update();
});
return PositionField(
layoutSize: widget.square,
children: system.map
);
}
}
你犯了一个大错:
build
方法必须永远不会有任何副作用,因为每当调用setState
时(或当某些更高的小部件更改,或者当用户旋转屏幕时...),它都会被再次调用。
相反,你想在Timer
中创建你的initState
,并在dispose
上取消它:
class TimerTest extends StatefulWidget {
@override
_TimerTestState createState() => _TimerTestState();
}
class _TimerTestState extends State<TimerTest> {
Timer _timer;
int _foo = 0;
// this is only called once when the widget is attached
@override
void initState() {
super.initState();
_timer = Timer.periodic(Duration(seconds: 1), (timer) => _update());
}
// stop the timer when the widget is detached and destroyed
@override
void dispose() {
_timer.cancel();
super.dispose();
}
void _update() {
setState(() {
_foo++;
});
}
@override
Widget build(BuildContext context) {
return Text('Foo: ${_foo}');
}
}