Reputation: 25
I'm trying to create a radio button widget. Everything is fine until I have to get the state of the button. (if it's clicked or not)
I made something really simple to get it, I created a bool variable in the StatefulWidget and I'm using it in the state class to update the widget when it gets clicked, and I return this variable with a function in the StatefulWidget.
It works well but it gives me this warning :
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)
But how am I supposed to access variable if I declare them in the state class?
I saw a lot of ways to deal with this problem but they all look way too much for a simple problem like this.
Here is my StatefulWidget :
class RadioButton extends StatefulWidget{
bool _isSelected = false;
bool isSelected() {
return _isSelected;
}
@override
_RadioButtonState createState() => new _RadioButtonState();
}
And my State :
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(),
)
);
}
}
and to access the variable, I declare the widget as a variable of my app class and I use the function isSelected on it :
RadioButton myRadio = new RadioButton();
...
print(myRadio.isSelected()); //For exemple
I could let this code but I want to learn the best way to do this.
Upvotes: 0
Views: 4462
Reputation: 723
The proposed way is also correct but preferred way is to have them in your State class as it maintains the State of your widget
Example :
class _RadioButtonState extends State<RadioButton> {
bool _isSelected = false;
bool isSelected() {
return _isSelected;
}
// other code here
}
Upvotes: 2
Reputation: 2077
The Widgets are Immutable in flutter, So you cannot modify the fields in the Radio widget.
you can only change the values in State class
you better assign the boolean value inside the State class and then use it.
Upvotes: 0