class - 这个类被标记为“@immutable”,但它的一个或多个实例字段不是最终的:
问题描述
如果我将变量声明为最终变量,那么我想要更改(按下时)的值(变量)就在其中,setState(){}
因此可以更改这些变量如何防止这种情况发生?
还有,为什么要写widget.value
?
我尝试使用 static 而不是 final 不起作用
class BottomCard extends StatefulWidget {
String title;
int value;
@override
_BottomCardState createState() => _BottomCardState(); }
class _BottomCardState extends State<BottomCard> {.....
....<Widget>[
FloatingActionButton(
elevation: 0,
child: Icon(FontAwesomeIcons.plus),
onPressed: () {
setState(() {
widget.value++;
});
},
backgroundColor: Color(0xFF47535E),
),
解决方案
如果您不需要从外部类获取变量(标题和值)。您可以在 _BottomCardState
课堂上声明它们并根据需要使用它们。喜欢这段代码。
class BottomCardState extends StatefulWidget {
@override
_BottomCardStateState createState() => _BottomCardStateState();
}
class _BottomCardStateState extends State<BottomCardState> {
int _value;
String title;
@override
void initState() {
super.initState();
_value = 0;
title = "any thing";
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
elevation: 0,
child: Icon(FontAwesomeIcons.plus),
onPressed: () {
setState(() {
_value++; // increment value here
});
},
),
);
}
}
如果您需要从其他类中获取变量(值和标题)。那么您需要将它们标记为 final 1。2-从构造函数中获取它们并访问它们的值,_BottomCardStateState
您需要使用它们来访问它们。它们widget._value
是最终的,您无法修改它们。喜欢这里的代码
class App extends StatelessWidget {
const App({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: BottomCardState(2,"some thing"),
);
}
}
class BottomCardState extends StatefulWidget {
final int _value;
final String title;
BottomCardState(this._value,this.title)
@override
_BottomCardStateState createState() => _BottomCardStateState();
}
class _BottomCardStateState extends State<BottomCardState> {
int value ;
@override
Widget build(BuildContext context) {
value = widget._value ;
return Scaffold(
floatingActionButton: FloatingActionButton(
elevation: 0,
child: Icon(FontAwesomeIcons.plus),
onPressed: () {
setState(() {
value++; // increment value here
});
},
),
);
}
}
推荐阅读
- android - 如何在 android studio 中修复 com.android.volley.ClientError
- javascript - 将数据从它阻塞的一个传递到另一个
- javascript - 如何使用 JavaScript 创建 .docx 文件而不是 .doc 单词
- html - CSS - 使背景图像成为链接
- c# - 附加加载场景并稍后销毁
- android - Mobile FireFox 在页面底部有固定内容的问题
- python - 改进运行时以减少列表 1 以仅包含与 python 中的列表 2 匹配的条目
- akka - 使用 jdbc 死信的持久演员
- javascript - 解构对象反应
- paypal - Paypal 争议沙盒测试,触发 CUSTOMER.DISPUTE.RESOLVED 事件