Home > Net >  Cannot get DropdownButton inside Dialog to update to new value on changed/selected
Cannot get DropdownButton inside Dialog to update to new value on changed/selected

Time:12-04

Here is what I have.

String selected = "ONE",

final List<DropdownMenuItem<String>> types = [
  DropdownMenuItem(value: "ONE", child: Text("ex1")),
  DropdownMenuItem(value: "TWO", child: Text("ex2")),
  ...
];

@override
Widget build(context) => Scaffold(
 body: Column(
  ...
  TextButton(
   onPressed: () {
    context: context,
    builder: (context) => AlertDialog(
     content: SizedBox(
      ...
      DropdownButton(
       items: types,
       value: selected,
       onChanged: (String? value) {
        selected = value!;
        setState(() {
         selected;
        });
      })

The widget is built as expected, but the dropdown menu does not update after a new value is selected. I know there are tons of similar questions out there, but the majority of solutions are

  • make sure the selected equivalence is globally defined
  • using setState()

both of which I have tried, but can't seem to get it working. I can confirm that selected is being set equal to value, just not being reflected on UI.

CodePudding user response:

Use StatefulBuilder to update ui inside dialog.

showDialog(
  context: context,
  builder: (context) => StatefulBuilder(
    builder: (BuildContext context, setStateSB) {
      return AlertDialog(
        content: DropdownButton(
            items: types,
            value: selected,
            onChanged: (String? value) {
              setStateSB(() {
                selected = value!;
              });
            }),
      );
    },
  ),
);
  • Related