【问题标题】:How to setState() on a ModalRoute?如何在 ModalRoute 上设置状态()?
【发布时间】:2019-11-24 01:56:04
【问题描述】:

我用 Flutter 编写了一个应用程序。我想更改字符串变量的状态。设置字符串变量的状态后,ModalRoute PopUpMenu 不显示更改的变量。如果我关闭 ModalRoute PopUpMenu 并再次打开它,我可以看到更改的变量。

我试图弹出上下文,但我想要在 PopUpMenu 上进行更改。我有自己的 Overlay 小部件。


    class MyOverlay extends ModalRoute {
    ...
    }

    // this is my main.dart: 

    List<String> categories = ['please', 'help', 'me'];
    String _selectedCategory = 'category';

    // this is where the PopUpMenu starts
    floatingActionButton: FloatingActionButton(
            child: ...,
            onPressed: () {
              _showPopup(context, _popupBody(), 'Add');
            },
    ),

    _showPopup(BuildContext context, Widget widget, String title, {BuildContext popupContext}) {
        Navigator.push(
          context,
          MyOverlay(
               ...
                  onPressed: () {
                    try {
                      Navigator.pop(context); //close the popup
                    } catch (e) {
                      print(e);
                    }
                  },
              ...
            body: widget,
       ) ...
      );
    }

    Widget _popupBody() {
        ...
        PopupMenuButton<String>(
                  // HERE IS THE PROBLEM THIS SHOULD CHANGE WHEN I SELECT 
                  child: Text('$_selectedCategory'),
                  itemBuilder: (BuildContext context) {
                    return categories.map((String choice) {
                      return PopupMenuItem<String>(
                        value: choice,
                        child: Text(choice),
                      );
                    }).toList();
                  },
                  onSelected: _selectCategory,
                ),

       ...
    }

    void _selectCategory(String category) {
        setState(() => this._selectedCategory = category);
    }

如果我选择 PopupMenuItem,文本小部件不会改变。

【问题讨论】:

  • 我也面临同样的问题..你能找到解决方案吗?

标签: text flutter dart refresh navigator


【解决方案1】:

我有同样的问题,我暂时使用 changedExternalState();强制重建,但我认为这可能不是最佳选择。

例子:

CheckboxListTile(
              value: _checkboxValue,
              title: Text(phone),
              onChanged: (value){
                _checkboxValue = value;
                //Fix
                changedExternalState();
              },
            )

【讨论】:

  • 哦,没见过 changedExternalState 方法。看起来像一个黑客解决方案,太棒了!
  • 这个方法怎么用?
  • @I_User - 我想要一个按钮来更新我的 ModalRoute。我将该 Button 设为有状态小部件,在构造函数中有一个 bool .. 然后我将在 ModalRoute 中更新的 bool 传递到该 Button 中,当 bool 更改时,我使用新值调用 setState,然后调用“changedExternalState() ;" - 就像上面的例子一样
猜你喜欢
  • 1970-01-01
  • 2016-06-21
  • 2021-11-27
  • 2012-07-04
  • 1970-01-01
  • 2019-10-20
  • 2021-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多