0

DropdownButton value is not updating after selecting values from DropdownItems. How to update default value with _selectedLocation?
The variables i use:

  String? stateToCountry;
  List? stateID;
  List? cityJson;
  Position? _position;
  String? currentAddress;
  Placemark? place;
    DropdownButton(
               hint:_selectedLocation==null ? Text('Dropdown') : Text(
                 _selectedLocation.toString(),
                 style: TextStyle(color: Colors.black),
               ),
              isExpanded: true,
              iconSize: 30,
              elevation: 16,
              underline: Container(
                height: 2,
                color: Colors.deepPurpleAccent,
              ),
              style: TextStyle(color: Colors.deepPurple, fontSize: 20.0),
              itemHeight: 50,
              items: countrylist!.map((location){
                return DropdownMenuItem(
                  value: location,
                  child: new Text(location["name"].toString()),

                );
              }).toList(),
              onChanged: (newValue){
                 setState(() {
                   _selectedLocation=newValue as String?;
                 });
              },

                ),
Ctnkaya
  • 15
  • 5
  • duplicate https://stackoverflow.com/questions/54044747/dropdownbutton-value-is-not-updating-after-selecting-values-from-dropdownitems?rq=1 – no_fate Sep 01 '21 at 14:29

2 Answers2

0

You need to set the value property,

DropdownButton(
  value: _selectedLocation,
  onChanged:(newValue){
      setState(() {
        _selectedLocation=newValue;
      });
  }
Nicolás López
  • 430
  • 2
  • 8
0

Dropdownbutton works as follows:

T represent a generic type, so you can pass a bool, String, double, YourCustomModel etc.

The Dropdownbutton needs 3 things:

  • The value T
  • A List<T> with the options,
  • The onChanged Function, which pass you the T value you select.

The widget, know which value is selected according as his instance, each object has an hashCode property which identify it from other objects, When you select an option, you must keep that instance.

That instance should be in your list, for example

final list=<String>[
'Hello', /// hashCode 1
'good bye', /// hashCode 2
'bye bye' /// hashCode 3
];

When you select one, this is pass through the onChanged, let's say you select the first option:

onChanged:(value){
print(value.hashCode); /// output value: 1
// you must keep that instance with the same type `T`
_selectedValue=value;
}

So now, your _selectedValue will be:

print(_selectedValue.hashCode);/// /// output value: 1
print(_selectedValue); /// output value: 'Hello'
Nicolás López
  • 430
  • 2
  • 8