Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter dropdownButton setState on change not updating dropdown text after selection to show selected item

I created a dropdownButton to allow users to select from a dropdown list which will be populated from an API. For now I am populating using a list I created.

Currently the button is displaying the items from my list but after a selection has been made the list doesnt show the selected item and still shows the hint text. What I would like to happen is after a selection has been made then the dropdownButton shows the item that was selected instead of the hint text.

in the onChanged method I added a setState in hopes of updating the _selectedValue variable to the value that was selected and displaying it in the dropdownButton.

I also added a print statement in my setState method and that does trigger and show me the value within the value variable.

Here is my code.

List<DropdownMenuItem<int>> listItems = [DropdownMenuItem(child: Text("2016"), value: 2016,), DropdownMenuItem(child: Text("2021"), value: 2021,)];
    int _selectedValue;

body: DropdownButton(
          value: _selectedValue,
          items: listItems,
          hint: Text("Select Year"),
          onChanged: (int value){
           setState(() {
             _selectedValue = value;
             print(value);
           });
          },
        ),
like image 831
Sebastian Flores Avatar asked Oct 16 '25 01:10

Sebastian Flores


1 Answers

Your code is fine, but the problem is maybe you are initializing the _selectedValue inside the build() method. So that whenever you call set state the widget rebuilds and initialize again with the default value.

int _selectedValue;
@override
Widget build(BuildContext context) {
    return DropdownButton(
    value: _selectedValue,
    items: listItems,
    hint: Text("Select Year"),
    onChanged: (int value){
      setState(() {
      _selectedValue = value;
      print(value);
    });    
},
),
like image 195
MBK Avatar answered Oct 19 '25 14:10

MBK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!