【问题标题】:How to change value of a stateful widget in flutter?如何在颤动中更改有状态小部件的值?
【发布时间】:2020-08-01 01:01:23
【问题描述】:

类 SecondScreen 扩展 StatefulWidget { int myIndexValue;

SecondScreen(this.myIndexValue);

@覆盖

  _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方法下。

【问题讨论】:

  • 请详细说明您要达到的目标。
  • 我正在尝试将 widget.myIndexValue 更改为任意数字。
  • @hellobear 你不能修改widget.X 因为它是最终的,你必须按照我在回答中提到的方式进行。
  • 想把你的编辑变成其他人的正确答案。

标签: flutter


【解决方案1】:
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());
  }
}

【讨论】:

  • 这不起作用,但可以理解。我想将状态变量设置为有状态的小部件值,例如var a = 小部件.a;此外,即使我这样做并尝试访问它,它也不会返回任何内容。
猜你喜欢
  • 2021-01-01
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 2019-10-06
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多