Create Item list for DropdownButton in Flutter

Issue

I’m back with another issue with the DropdownButton.

The DropdownButton is not enabled. I found this in api.flutter.dev

If the onChanged callback is null or the list of items is null then
the dropdown button will be disabled, i.e. its arrow will be displayed
in grey and it will not respond to input.

Here is my code now:

return new DropdownButton<String>(
                            hint: new Text("Select Agency"),
                            value: _currentAgency,
                            onChanged: changedDropDownAgency,
                            items: snapshot.data.docs.forEach((document) {
                              return new DropdownMenuItem<String>(
                                value: document.data()['name'],
                                child: new Text(document.data()['name']),
                              );
                            }),
                          );

void changedDropDownAgency(String selected_agency) {
    setState(() {
      _currentAgency = selected_agency;
    });
    globals.selectedAgency = selected_agency;
  }

The forEach loop runs fine and in debug mode I can see that there is data in the document object. I don’t know how to debug the DropdownButton code to see why the button is not active. Any suggestions would be helpful.
Thanks.

Solution

forEach() on Iterables does not return any value (see: https://api.dart.dev/stable/2.10.5/dart-core/Iterable/forEach.html), and thus items is null and the DropdownButton is disabled. Use map instead (https://api.dart.dev/stable/2.10.5/dart-core/Iterable/map.html). Example:

snapshot.data.docs.map<DropdownMenuItem<String>>((document) {
    return new DropdownMenuItem<String>(
        value: document.data()['name'],
        child: new Text(document.data()['name']),
    );
}).toList(),

Answered By – puelo

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *