flutterdartdrop-down-menu

CustomDropdown with display name and code


I am using a widget called CustomDropdown from the animated_custom_dropdown 3.1.1 package.

Here's my current structure:

List<Map<String, dynamic>> data

[
    {
        "code": "140100000",
        "name": "Abra"
    },
    {
        "code": "160200000",
        "name": "Agusan del Norte"
    },
    {
        "code": "160300000",
        "name": "Agusan del Sur"
    },
    {
        "code": "060400000",
        "name": "Aklan"
    },
    {
        "code": "050500000",
        "name": "Albay"
    }
]

CustomDropDown widget

CustomDropdown<
    Map<String, dynamic>>.search(
  validateOnChange: true,
  canCloseOutsideBounds: true,
  decoration: CustomDropDownStyle
      .customDropdownSearchDecorationClass(
          context,
          isDarkMode), // to write code once
  items: address,
  initialItem:
      address[0],
  hintText: "Select one",
  onChanged: (value) {
    final valueCode = value?['code'];
    debugPrint(
        'Selected province $valueCode');
  },
)

Unexpected output

CustomDropdown

What I'm trying to achieve is to display only the name in the CustomDropdown list. However, if the user selects a specific province, it should then pass a corresponding code.

The crucial part is the code because it uniquely corresponds to the next address type. However, users should only see the name, not the List<Map<String, dynamic>> data format list.

Yet I have no idea what to do here.

Thanks in advance!


Solution

  • Here's my workaround

    I've added these two properties:

    listItemBuilder: (context, item,
            isSelected, onItemSelect) =>
        Text(item['name']),
    headerBuilder: (context,
            selectedItem, enabled) =>
        Text(selectedItem['name']),
    

    Which will then be like this:

    CustomDropdown<
        Map<String, dynamic>>.search(
      validateOnChange: true,
      canCloseOutsideBounds: true,
      decoration: CustomDropDownStyle
          .customDropdownSearchDecorationClass(
              context,
              isDarkMode), // to write code once
      items: address,
      initialItem:
          address[_defaultDropdownIndex],
      hintText: "Select one",
      listItemBuilder: (context, item,
              isSelected, onItemSelect) =>
          Text(item['name']),
      headerBuilder: (context,
              selectedItem, enabled) =>
          Text(selectedItem['name']),
      onChanged: (value) {
        final valueCode = value?['code'];
        debugPrint(
            'Selected province $valueCode');
      },
    )
    

    Eventually, the problem was solved, and here's the expected output:

    CustomDropdown-fixed

    If I selected Abra:

    I/flutter ( 1234): Selected province 140100000