List<Map<String, dynamic>> category = [
   {
     "name": "One",
     "detail": ['11', '12', '13', '14'],
     "department": "aaa",
   },
   {
     "name": "two",
     "detail": ['21', '22', '23', '24'],
     "department": "bbb",
   },
   {
     "name": "three",
     "detail": ['31', '32', '33', '34'],
     "department": "ccc",
   },
   {
     "name": "four",
     "detail": ['41', '42', '43', '44'],
     "department": "aaa",
   },
   {
     "name": "five",
     "detail": ['41', '42', '43', '44'],
     "department": "aaa",
   },
 ];

for (final item in category) {
       if (item["department"] == "aaa") {
         for (final value in item.values) {
           if (value is List) {
             for (final listValue in value) {
               data.add({'value': listValue, 'bold': false});
             }
           } else {
             data.add({'value': item['department'], 'bold': true});
           }
         }
       }
     }

enter image description here

enter image description here

I have used the above (loop) method to doing the dropdown, but the category "name" will repeat many times, as shown in first picture

May I know how to make the list category be like the second picture dropdown, for example, the name will be the label, detail will be item of the label. Lastly, the 'department' is for classify showing which data, let say I want to show the data that department is 'aaa' means that 3 list data will be shown in the dropdown item.


Solution 1: usualprogrammer_123

Looking at your data named as "category" which is a list of Maps, I think you can add labels and achieve the required functionality that includes using custom variable in the following way:

const dept = 'aaa';

final data = category.where((element) => element['department'] == dept);

List<DropdownMenuItem<String>>? get_items() {
  final List<DropdownMenuItem<String>> _dropdownItems1 = [];

  for (final val in data) {
    for (final value in val.values) {
      if (value is List) {
        for (final listValue in value) {
          _dropdownItems1.add(
            DropdownMenuItem(
              child: Text(listValue),
              value: listValue,
            ),
          );
        }
      } else if (value != dept) {
        _dropdownItems1.add(DropdownMenuItem(
          child:
              Text(value, style: const TextStyle(fontWeight: FontWeight.bold)),
          value: value,
        ));
      }
    }
  }

  return _dropdownItems1;
}

Now, in the dropdownbutton you can simply call "get_items()" to get the dropdown menu items for creating the dropdown menu. It can be done as mentioned in the code below.

   DropdownButton<String>(
                  value: selectedItem,
                  items: get_items(),
                  onChanged: (value) {
                    setState(() {
                      selectedItem = value;
                    });
                  }),

The output will be as follows:

Output Dropdown menu