首页 > 解决方案 > How to prevent changes in a dropdown in Flutter?

问题描述

I tried to ask the user, if he is sure to change the data after pressing on a dropdown menu.

Currently, I launch an alert dialog after onChanged. Asking the user "Are you sure to change data ?". If Yes , I save the data changes. If "No", I close the alert dialog.

But if user chooses "No", the data has been changed and I don't want to change the data... How can I stop the change? I have a complicated solution where I save all data change, and when the user presses NO, I load the last data save before "NO" but I found this to complicated. Are there any other, more simple solution ? Thank you

Here is my code :

new DropdownButton<String>(
    onChanged: (String changedValue) {
        dialog(); //lanche dialog with choice of data modification
        data=changedValue;
        setState(() {
            data;
            });
        },
        value: data,
        items: <String>['data1', 'data2', 'data3','data4', 'data5']
             .map((String changedValue) {
                 return new DropdownMenuItem<String>(
                     value: changedValue,
                     child: new Text(changedValue),
                     );
             }).toList()),

标签: dartflutterdropdown

解决方案


您应该更新决策函数中的 setState 数据值。检查以下代码。

new DropdownButton<String>(
  onChanged: (String changedValue) {
    _showDialog(changedValue); // I changed this.
  },
  value: data,
  items: <String>['data1', 'data2', 'data3', 'data4', 'data5']
    .map((String changedValue) {
      return new DropdownMenuItem<String>(
        value: changedValue,
        child: new Text(changedValue),
      );
}).toList()),




void _showDialog(selection) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: new Text("Alert Dialog title"),
        content: new Text("Alert Dialog body"),
        actions: <Widget>[
          new FlatButton(
            child: new Text("No"),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          new FlatButton(
            child: new Text("Yes"),
            onPressed: () {
              // this is where data value updates.
              setState(() {
                data = selection;
              });
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}

推荐阅读