簡體   English   中英

在 StatefulWidget Flutter 中訪問變量的最佳方式

[英]Best way to access variable in StatefulWidget Flutter

我正在嘗試創建一個單選按鈕小部件。 一切都很好,直到我必須獲得按鈕的狀態。 (如果它被點擊或沒有)

我做了一些非常簡單的事情來獲取它,我在 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)

但是如果我在 state 類中聲明它們,我應該如何訪問變量?

我看到了很多處理這個問題的方法,但對於像這樣的簡單問題來說,它們看起來都太多了。

這是我的 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

我可以讓這個代碼,但我想學習最好的方法來做到這一點。

建議的方法也是正確的,但首選方法是將它們放在 State 類中,因為它維護小部件的狀態

例子 :

class _RadioButtonState extends State<RadioButton> {

  bool _isSelected = false;

  bool isSelected() {
    return _isSelected;
  }
  // other code here

}
  1. 小部件在顫動中是不可變的,因此您無法修改 Radio 小部件中的字段。

  2. 您只能更改 State 類中的值

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM