【问题标题】:Best way to access variable in StatefulWidget Flutter在 StatefulWidget Flutter 中访问变量的最佳方式
【发布时间】: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

我可以让这个代码,但我想学习最好的方法来做到这一点。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    建议的方法也是正确的,但首选方法是将它们放在您的 State 类中,因为它维护您的小部件的状态

    例子:

    class _RadioButtonState extends State<RadioButton> {
    
      bool _isSelected = false;
    
      bool isSelected() {
        return _isSelected;
      }
      // other code here
    
    }
    

    【讨论】:

    • 我喜欢这个版本,但是如何访问 StatefulWidget 类中的状态?
    • 如果你想从你的父窗口小部件类中访问任何变量,你可以通过从 widget.variableName 调用它,以你之前所做的方式轻松调用它
    【解决方案2】:
    1. 小部件在颤振中是不可变的,所以你不能修改 Radio 小部件中的字段。

    2. 只能更改 State 类中的值

    3. 您最好在 State 类中分配布尔值,然后使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-29
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2021-05-16
      • 2015-09-06
      • 1970-01-01
      相关资源
      最近更新 更多