如何在 ModalRoute 上 setState()?

use*_*497 5 text refresh navigator dart flutter

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

我尝试弹出上下文,但我希望在 PopUpMenu 上进行更改。我有自己的覆盖小部件。


    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);
    }

Run Code Online (Sandbox Code Playgroud)

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

小智 6

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

例子:

CheckboxListTile(
              value: _checkboxValue,
              title: Text(phone),
              onChanged: (value){
                _checkboxValue = value;
                //Fix
                changedExternalState();
              },
            )
Run Code Online (Sandbox Code Playgroud)