gpt4 book ai didi

flutter - Flutter:如何为StatefulWidget创建非最终属性?

转载 作者:行者123 更新时间:2023-12-03 02:49:40 24 4
gpt4 key购买 nike

假设我要创建一个按钮,每次单击它都会更改颜色。
在构造函数中,其开始颜色是必需的。

以下代码可以正常工作,但是当我将鼠标悬停在TestButton上方时,会收到以下消息:“该类(或该类继承的类)被标记为'@immutable',但是其一个或多个实例字段未标记为最终:TestButton.color”。

如果它应该是最终的但我需要更改,那么解决方案是什么?
无论如何,为什么它是最终的?

class TestButton extends StatefulWidget {
TestButton({this.color});
Color color;
@override
_TestButtonState createState() => _TestButtonState();
}

class _TestButtonState extends State<TestButton> {
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () {
setState(() {
widget.color = widget.color == Colors.red ? Colors.blue : Colors.red;
});
},
child: Icon(
Icons.add,
size: 80,
),
color: widget.color,
);
}
}

最佳答案

您可以在StateStatefulWidget对象中拥有变量,而不是StatefulWidget本身具有变量。

如果需要从另一个窗口小部件传递值,则可以传递它,并将其重新分配给State函数中的initState变量。

例:

class TestButton extends StatefulWidget {
TestButton({this.passedcolor});
final Color passedColor;
@override
_TestButtonState createState() => _TestButtonState();
}

class _TestButtonState extends State<TestButton> {
Color color;

@override
initState(){
color = widget.passedColor;
super.initState()
}

@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () {
setState(() {
color = color == Colors.red ? Colors.blue : Colors.red;
});
},
child: Icon(
Icons.add,
size: 80,
),
color: color,
);
}
}

然后您可以使用 setState将其更新为所需的任何颜色。

至于为什么在构造函数中传递的值必须是 final或为什么不能更改它,是因为 StatefulWidget本身是不可变的并且保存不可变的数据,但是它还保存了一个可变的 State对象,该对象存储了所有 aka mutable data状态小部件需要。

引用Flutter文档:

StatefulWidget instances themselves are immutable and store their mutable state either in separate State objects that are created by the createState method, or in objects to which that State subscribes, for example Stream or ChangeNotifier objects, to which references are stored in final fields on the StatefulWidget itself.



您可以在这里阅读更多内容:
StatefulWidget class documentation on Flutter website

关于flutter - Flutter:如何为StatefulWidget创建非最终属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60475076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com