如何仅为DropdownButtonFormField中的DropdownMenuItem添加后缀图标?
要实现下拉按钮仅显示字符串、下拉选项带关闭图标的效果,核心是利用DropdownButtonFormField的selectedItemBuilder属性,单独定义选中项的展示样式,和下拉菜单的选项样式区分开。
修改后的完整代码如下:
SizedBox( width: kWidth * 0.1, child: DropdownButtonFormField( focusColor: Colors.transparent, decoration: InputDecoration( filled: true, fillColor: Colors.transparent, focusColor: Colors.transparent, hoverColor: Colors.transparent, border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: kBlack), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: kBlack), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: kBlack), ), disabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: kBlack), ), focusedErrorBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: kBlack), ), errorBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: kBlack), ), ), value: homePageViewModel.selectedDistrict.value, // 自定义选中项的展示,仅显示文本 selectedItemBuilder: (BuildContext context) { return homePageViewModel.districtList.map((String value) { return Text(value); }).toList(); }, items: homePageViewModel.districtList.map<DropdownMenuItem<String>>((String value) { return DropdownMenuItem<String>( value: value, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text(value), // 给图标添加点击移除逻辑 GestureDetector( onTap: () { homePageViewModel.districtList.remove(value); // 若删除的是当前选中项,重置选中值 if (homePageViewModel.selectedDistrict.value == value) { homePageViewModel.selectedDistrict.value = homePageViewModel.districtList.isNotEmpty ? homePageViewModel.districtList.first : null; } homePageViewModel.notifyListeners(); }, child: const Icon( Icons.close, color: kBlack, ), ), ], ), ); }).toList(), onChanged: (value) { homePageViewModel.selectedDistrict.value = value!; }, ), );
关键说明:
- 选中项样式分离:通过
selectedItemBuilder回调,返回仅包含文本的Widget,让下拉按钮的选中区域只显示字符串,和下拉选项的带图标样式区分开。 - 移除选项逻辑:给关闭图标包裹
GestureDetector,点击时从列表中移除对应项,并同步处理选中值(避免选中已删除的项),最后通知状态更新。
内容的提问来源于stack exchange,提问作者Senthur Kumaran
相关产品推荐
相关产品推荐

