简体   繁体   中英

Best way to access variable in StatefulWidget Flutter

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.

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

}
  1. The Widgets are Immutable in flutter, So you cannot modify the fields in the Radio widget.

  2. you can only change the values in State class

  3. you better assign the boolean value inside the State class and then use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM