【发布时间】:2020-06-11 11:19:05
【问题描述】:
我正在尝试创建一个单选按钮小部件。 一切都很好,直到我必须获得按钮的状态。 (如果它被点击了)
我做了一些非常简单的事情来获得它,我在 StatefulWidget 中创建了一个 bool 变量,并在状态类中使用它来在它被点击时更新小部件,然后我用 StatefulWidget 中的函数返回这个变量.
效果很好,但它给了我这个警告:
This class (or a class that this class inherits from) is marked as '@immutable', but one or more of its instance fields aren't final: RadioButton._isSelecteddart(must_be_immutable)
但是如果我在状态类中声明变量,我应该如何访问它们?
我看到了很多解决这个问题的方法,但对于这样一个简单的问题,它们看起来都太过分了。
这是我的 StatefulWidget:
class RadioButton extends StatefulWidget{
bool _isSelected = false;
bool isSelected() {
return _isSelected;
}
@override
_RadioButtonState createState() => new _RadioButtonState();
}
还有我的国家:
class _RadioButtonState extends State<RadioButton> {
void _changeSelect(){
setState(() {
widget._isSelected = !widget._isSelected;
});
}
@override
Widget build(BuildContext context){
return GestureDetector(
onTap: _changeSelect,
child: Container(
width: 16.0,
height: 16.0,
padding: EdgeInsets.all(2.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(width: 2.0, color: Colors.black)),
child: widget._isSelected
? Container(
width: double.infinity,
height: double.infinity,
decoration:
BoxDecoration(shape: BoxShape.circle, color: Colors.black),
)
: Container(),
)
);
}
}
为了访问变量,我将小部件声明为我的应用程序类的变量,并在其上使用函数 isSelected:
RadioButton myRadio = new RadioButton();
...
print(myRadio.isSelected()); //For exemple
我可以让这个代码,但我想学习最好的方法来做到这一点。
【问题讨论】: