如何在flutter中更改有状态小部件的值?

时间:2020-04-18 13:39:16

标签: flutter

SecondScreen类扩​​展了StatefulWidget { int myIndexValue;

SecondScreen(this.myIndexValue);

@override

  _SecondScreenState createState() => _SecondScreenState();
}

class _MusicPlayingState extends State<MusicPlaying> {
  @override
  void initState() {
    super.initState();
    setState({
      widget.myIndexValue = widget.myIndexValue + 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text(widget.myIndexValue.toString());
  }

}

编辑:我找到了答案。将打印语句无处不在之后。我发现状态小部件的构建功能经常被调用。因此,我将setstate放入函数中,并将其置于build方法下。

1 个答案:

答案 0 :(得分:0)

class SecondScreen extends StatefulWidget {
  final int myIndexValue;

  SecondScreen(this.myIndexValue);

  @override
  _SecondScreenState createState() => _SecondScreenState();
}

class _SecondScreenState extends State<SecondScreen> {
  int _myIndexValue;

  @override
  void initState() {
    super.initState();
    _myIndexValue = widget.myIndexValue;
    _update();
  }

  void _update() {
    setState(() {
      _myIndexValue = _myIndexValue + 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text(_myIndexValue.toString());
  }
}