from dropdownmenu to dropdownsearch in flutter

Viewed 575

I was using normal dropdown menu in my project with small amount of data fetched from my api, but now i have menu which could reach hundred of values and make it hard to select an item. That's why i wanted to use DropDownSearch but instead i get an error

Normal dropdown code which works very fine

 DropdownButton(
              showSearchBox: true,
              showSelectedItem: true,
              items: data3.map((item) {
                return new DropdownMenuItem(
                  child:  Text(item['first_name']+" "+ item['last_name']),
                  value: item['emp_code'].toString(),
                );
              }).toList(),
              onChanged: (newVal) {
                setState(() {
                  _mySelection3 = newVal.toString();
                });
              },
              value: _mySelection3,
            ),

data3 = [{emp_code: 111, first_name: adnen, last_name: hamouda}, {emp_code: 666, first_name: ahmed, last_name: ahmed 99}....

this is the result: normal dropdown

But when i tried to convert it to dropDownSearch i got this result: search dropdown I want to show the first_name and last_name like the normal dropdown but save the value of their 'emp_code' which i will be using in another api later. How can i fix it ?

 DropdownSearch(
              mode: Mode.DIALOG,
              showSearchBox: true,
              items: data3.map((item) {
                return new DropdownMenuItem(
                  child:  Text(item['first_name']+" "+ item['last_name']),
                  value: item['emp_code'].toString(),
                );
              }).toList(),
              onChanged: (newVal) {
                setState(() {
                  print(data3);
                  _mySelection3 = newVal.toString();
                });
              },
              selectedItem: _mySelection3,

            ),
1 Answers

Here is the way I found to use searchable dropdown lists.

I tried dropdown_search package at first, but it seems the documentation and examples related with the latest version (5.0.2) are depreciated. Later on, I moved to dropdown_button2 and I am happy the way the DropdownButtonFormField2 was implemented, because it is very similar which I have done to the flutter DropdownButtonFormField implementation, so far.

Have a look at the Flutter bundled DropdownButtonFormField example:

return DropdownButtonFormField<SetorTemp>(
                    decoration: const InputDecoration(
                        labelText: 'Setor institucional'),
                    isExpanded: true,
                    icon: const Icon(Icons.arrow_downward),
                    items: snapshot.data!
                        .map((SetorTemp rtItem) =>
                            DropdownMenuItem<SetorTemp>(
                              value: rtItem,
                              child: Text(
                                '${rtItem.nome} (${rtItem.sigla})',
                                softWrap: true,
                              ),
                            ))
                        .toList(),
                    hint: Text(
                        '${selectedSetorTemp.nome} (${selectedSetorTemp.sigla})'),
                    onChanged: (SetorTemp? newValue) {
                      setState(() {
                        // do your logic here!
                        selectedSetorTemp = newValue;
                      });
                    },
                  );

And the DropdownButtonFormField2 using dropdown_button2 package

return DropdownButtonFormField2<SetorTemp>(
                    decoration: const InputDecoration(
                        labelText: 'Setor institucional'),
                    isExpanded: true,
                    icon: const Icon(Icons.arrow_downward),
                    items: snapshot.data!
                        .map((SetorTemp rtItem) =>
                            DropdownMenuItem<SetorTemp>(
                              value: rtItem,
                              child: Text(
                                '${rtItem.nome} (${rtItem.sigla})',
                                softWrap: true,
                              ),
                            ))
                        .toList(),
                    hint: Text(
                        '${selectedSetorTemp.nome} (${selectedSetorTemp.sigla})'),
                    onChanged: (SetorTemp? newValue) {
                      setState(() {
                        // Do your logic here!
                        selectedSetorTemp = newValue;
                      });
                    },
                    // Search implementation using dropdown_button2 package
                    searchController: searchContentSetor,
                    searchInnerWidget: Padding(
                      padding: const EdgeInsets.only(
                        top: 8,
                        bottom: 4,
                        right: 8,
                        left: 8,
                      ),
                      child: TextFormField(
                        controller: searchContentSetor,
                        decoration: InputDecoration(
                          isDense: false,
                          contentPadding: const EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 8,
                          ),
                          labelText: 'Setor institucional',
                          hintText: 'Parte do nome do setor...',
                          counterText: '',
                          hintStyle: const TextStyle(fontSize: 16),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                      ),
                    ),
                    searchMatchFn: (rtItem, searchValue) {
                      return (rtItem.value.nome
                          .toLowerCase()
                          .contains(searchValue.toLowerCase()));
                    },
                    //This to clear the search value when you close the menu
                    onMenuStateChange: (isOpen) {
                      if (!isOpen) {
                        searchContentSetor.clear();
                      }
                    },
                  );

They are similar at first:

enter image description here

However, after clicking they will show their differences from the initial implementation:

enter image description here

To the dropdown_button2 package:

enter image description here

The selectedSetorTemp variable is of the type SetorTemp and the model I have used is:

class SetorTemp {
  final int id;
  final String? nome;
  final String? sigla;
  SetorTemp({required this.id, this.nome, this.sigla});

  factory SetorTemp.fromJson(Map<String, dynamic> json) {
    return SetorTemp(
      id: json['id'] as int,
      nome: json['nome'] as String,
      sigla: json['sigla'] as String,
    );
  }

  Map<String, dynamic> toJson() => {
        'nome': nome,
        'sigla': sigla,
      };
}
Related