【问题标题】:Flutter/Dart - Dropdown value not changing颤振/飞镖 - 下拉值不变
【发布时间】:2020-11-09 11:40:58
【问题描述】:

我创建了一个下拉菜单并用值填充它,但是当我选择一个时,所选值不会改变。我知道这是 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')
    );
  }

有什么建议吗?谢谢

【问题讨论】:

  • 尝试在 selectedOccasion 中设置一个默认值(数组值之一)

标签: flutter dart


【解决方案1】:

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

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

【讨论】:

  • 即使我的页面是有状态小部件,我还需要这样做吗?谢谢
  • 是的,在dropdown里面调用setState会更新整个页面而不是DropdownButton,所以你需要用statefulbuilder包装一下。
猜你喜欢
  • 1970-01-01
  • 2020-12-25
  • 2020-11-05
  • 2019-05-07
  • 2021-03-11
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
  • 2020-05-15
相关资源
最近更新 更多