如何从Flutter对话框内的一个单独类中返回下拉框的值

huangapple go评论48阅读模式
英文:

How to return dropdown value from a separate class inside a Flutter Dialog

问题

如何刷新UI并将所选值返回到对话框中?

要刷新UI并将所选值返回到对话框中,您可以采取以下步骤:

  1. 通过StatefulBuilder在对话框中包装MyDropDown小部件,以便您可以在对话框内部改变状态。
  2. MyDropDown小部件的onChanged回调中,使用setState函数来更新状态。
  3. 在对话框中的"Save"按钮上调用一个函数,该函数将所选值返回到对话框的调用者。

以下是您可以执行的更改:

Future<void> ShowDialog(context) async {
  var DataType;
  var DropDownValue;

  await showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(builder: (context, setStateAB) {
          return AlertDialog(
            scrollable: true,
            title: Text('Test Dialog'),
            content: MyDropDown(DataType, DropDownValue, (selectedValue) {
              setStateAB(() {
                DropDownValue = selectedValue;
              });
            }),
            actions: [
              ElevatedButton.icon(
                onPressed: () {
                   // Call a function to save, including the DropDownValue
                   // You can use DropDownValue here to access the selected value
                },
                icon: Icon(
                  Icons.save,
                  size: 24.0,
                ),
                label: Text('Save'),
              ),
              ElevatedButton.icon(
                onPressed: () {},
                icon: Icon(
                  Icons.cancel,
                  size: 24.0,
                ),
                label: Text('Cancel'),
              ),
            ],
          );
        });
      });
}

Widget MyDropDown(type, val, Function(String) onChanged) {
  // Get http data according to type
  return DropdownButton<String>(
    value: val,
    isExpanded: true,
    items: <String>['One', 'Two', 'Free', 'Four']
        .map<DropdownMenuItem<String>>((String value) {
      return DropdownMenuItem<String>(
        value: value,
        child: Text(value),
      );
    }).toList(),
    onChanged: (String? selectedValue) {
      onChanged(selectedValue!); // Call the provided onChanged function
    },
  );
}

通过这些更改,您将能够在用户选择下拉列表项时更新状态,并在"Save"按钮点击时访问所选值。

英文:

I would like to add a dropdown (or more in some cases) in a pop up dialog. In order to manage all dropdowns in the entire app and make the coding of the UI more simpler, I separate the dropdown Widget to another dart file. I am not able to refresh the UI when the selection of the dropdown is changed, and I am not able to get the value back to the dialog box for future processing.

class _MyHomePageState extends State&lt;MyHomePage&gt; {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: TextButton(
        onPressed: () {
          ShowDialog(context);
        },
        child: Text(&#39;Show Dialog&#39;),
      ),
    );
  }
}

Future&lt;void&gt; ShowDialog(context) async {
  var DataType;
  var DropDownValue;
  await showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(builder: (context, setStateAB) {
          return AlertDialog(
            scrollable: true,
            title: Text(&#39;Test Dialog&#39;),
            content: MyDropDown(DataType, DropDownValue),
            actions: [
              ElevatedButton.icon(
                onPressed: () {
                   // call function to save including the DropDownValue
                },
                icon: Icon(
                  Icons.save,
                  size: 24.0,
                ),
                label: Text(&#39;Save&#39;),
              ),
              ElevatedButton.icon(
                onPressed: () {},
                icon: Icon(
                  Icons.cancel,
                  size: 24.0,
                ),
                label: Text(&#39;Cancel&#39;),
              ),
            ],
          );
        });
      });
}

Widget MyDropDown(type, val) {
  //get http data according to type
  return DropdownButton&lt;String&gt;(
    value: val,
    isExpanded: true,
    //below items for testing only
    items: &lt;String&gt;[&#39;One&#39;, &#39;Two&#39;, &#39;Free&#39;, &#39;Four&#39;]
        .map&lt;DropdownMenuItem&lt;String&gt;&gt;((String value) {
      return DropdownMenuItem&lt;String&gt;(
        value: value,
        child: Text(value),
      );
    }).toList(),
    onChanged: (String? selectedvalue) {
      val = selectedvalue!;
    },
  );
}


How can I refresh the UI and return the selected value back to dialog?

答案1

得分: 1

你可以将回调函数传递给你的MyDropDown小部件。

return AlertDialog(
  ...,
  content: MyDropDown(
    DataType, 
    DropDownValue,
    (String? selectedValue) => DropDownValue = selectedValue,
  ),
  ...,
);
Widget MyDropDown(type, val, onChanged) {
  return DropdownButton<String>(
    ...,
    onChanged: (String? selectedvalue) {
      val = selectedvalue!;
      onChanged(selectedvalue);
    },
  );
}
英文:

You could pass callback function to your MyDropDown widget.

return AlertDialog(
  ...,
  content: MyDropDown(
    DataType, 
    DropDownValue,
    (String? selectedValue) =&gt; DropDownValue = selectedValue,
  ),
  ...,
);
Widget MyDropDown(type, val, onChanged) {
  return DropdownButton&lt;String&gt;(
    ...,
    onChanged: (String? selectedvalue) {
      val = selectedvalue!;
      onChanged(selectedvalue);
    },
  );
}

答案2

得分: 0

我看到你没有使用下拉菜单中声明的状态。总的来说,这就是要点。

// 更新下拉菜单内外的UI,像这样
...
onChange:...
setState(() { }); // 更新主(UI)状态
setStateAB((){}); // 更新内部UI
....

你可以创建一个变量,用来保存这两个状态中的值。

英文:

I see you haven't used the state that you declared in the dropdown menu.all in all this is the gist

//update the ui of both inside the dropdown and outside like this
...
onChange:...
setState(() { }); // update the main(state) UI
  setStateAB((){});//update the inner UI

....

You could create variable that would hold the value inside both of the states also

huangapple
  • 本文由 发表于 2023年3月1日 10:42:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75599120.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定