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

时间:2019-04-21 18:41:07

标签: flutter flutter-layout

我有一个带有定期更改数据的窗口小部件,并且我使用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
    );
  }
}

1 个答案:

答案 0 :(得分: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}');
  }
}
相关问题