繁体   English   中英

Flutter/Dart - 下拉值不变

[英]Flutter/Dart - Dropdown value not changing

我创建了一个下拉菜单并用值填充它,但是,当我选择一个时,选定的值不会改变。 我知道这是 SO 上的一个常见问题,但我尝试了很多解决方案,但都没有帮助。 这是我的代码:

  String selectedOccasion;

  @override
  Widget build(BuildContext context) {
    final collectionProvider = Provider.of<CollectionProvider>(context).allOccasions;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.deepPurpleAccent,
        title: Text('Viewer'),
        actions: [
          Stack(
            children: [
              IconButton(
                  icon: Icon(Icons.add),
                  onPressed: () {
                    showDialog(
                        context: context,
                        builder: (context) {
                          return AlertDialog(
                            title: Text("Add to collection"),
                            content: DropdownButton<String>(
                              hint: Text('Select Occasion'),
                              value: selectedOccasion,
                              items: collectionProvider.map((String value) {
                                return new DropdownMenuItem<String>(
                                  value: value,
                                  child: new Text(value),
                                );
                              }).toList(),
                              onChanged: (String newValue) {
                                setState(() {
                                  selectedOccasion = newValue;
                                });
                              },),
                          );
                        });
                  })
            ],
          )
        ],
      ),
      body: Container(child: Text('Body')
    );
  }

有什么建议? 谢谢

您需要将 DropdownButton 转换为有状态的小部件。 所以 setState 会起作用。 所有其他代码都可以正常工作。

   StatefulBuilder(
                  builder: (context, setState) {
                    DropdownButton()
                  })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM