1
votes

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);
           });
          },
        ),
1
I open new flutter project and tried your code, its working just fine, Maybe you have something else in your code is the problem, that you didn't share with us hereMod

1 Answers

2
votes

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);
    });    
},
),