关于animated_custom_dropdown 3.1.1中CustomDropdown组件仅显示名称并传递对应code值的实现问题
animated_custom_dropdown 3.1.1中CustomDropdown组件仅显示名称并传递对应code值的实现问题
Got it, I see exactly what you're facing here! The issue is that the CustomDropdown is defaulting to displaying the entire Map as a string since you haven't told it how to format each list item for display. Luckily, this package has a built-in way to fix this with the itemAsString parameter.
Here's how to fix your code:
You just need to add the itemAsString callback to your CustomDropdown.search() widget. This callback lets you define exactly what text should be shown for each list item, while keeping the full Map (with both name and code) intact for your selection logic.
CustomDropdown<Map<String, dynamic>>.search( validateOnChange: true, canCloseOutsideBounds: true, decoration: CustomDropDownStyle .customDropdownSearchDecorationClass( context, isDarkMode), items: address, initialItem: address[0], hintText: "Select one", // 关键:指定下拉列表中要显示的文本 itemAsString: (item) => item['name'] ?? 'Unknown', onChanged: (value) { final valueCode = value?['code']; debugPrint( 'Selected province $valueCode'); }, )
Let's break down what this does:
itemAsString: (item) => item['name'] ?? 'Unknown': This tells the dropdown to take eachMapitem from your list, extract thenamefield, and display that as the visible text. The?? 'Unknown'is a safety fallback in case anameis missing in your data.- Your
onChangedcallback still receives the fullMapobject, so you can still accessvalue?['code']just like before to get the unique code for your next address step. - Users will only see clean province names in the dropdown list and selected display — no raw
Mapformat clutter.
Extra tips:
- The selected item's display will also automatically use the
nametext, so you don't need extra code for that. - If you're sure all your data entries have a valid
namefield, you can skip the?? 'Unknown'fallback, but it's good practice to handle edge cases.
This should perfectly match what you're trying to achieve! 😊
内容来源于stack exchange
相关产品推荐
相关产品推荐

