有没有更好的方法来不断重建小部件?

问题描述 投票:0回答:1

我有小部件,数据定期更改,我正在使用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
    );
  }
}
flutter flutter-layout
1个回答
0
投票

你犯了一个大错:

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}');
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.