如何在 ModalRoute 上 setState()?

问题描述 投票:0回答:2

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

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

text flutter dart refresh navigator
2个回答
6
投票

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

示例:

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

0
投票

例如:

class MyOverlaySW extends StatefulWidget {
  ...
}

class MyOverlaySWState extends State<MyOverlaySW> {
  ...
}

class MyOverlay extends ModalRoute {
  ...
  @override
  Widget buildPage(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    return MyOverlaySW();
  }
}

总之,在

StatefulWidget
函数中返回一个
buildPage
即可。

© www.soinside.com 2019 - 2024. All rights reserved.