3

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);
           });
          },
        ),
Sebastian Flores
  • 101
  • 2
  • 12
  • 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 here – Mod Feb 11 '21 at 02:08

2 Answers2

9

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);
    });    
},
),
MBK
  • 2,589
  • 21
  • 25
0

In case anyone else is having this issue, I had the same issue and it was driving me nuts and I was using setState() appropriately etc., It was 100% where I was defining the "initialValue" property.

I was defining it right inside the build method. That did not work, even though I had the same setup in a sister module and it indeed did work. Not sure why that is.

Once I changed the definition of that variable to the state class, it worked like a charm. Hope it saves some, some cycles.

ctacta1
  • 67
  • 1
  • 8
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 29 '22 at 06:29