Flutter中如何在Dropdown下拉框内显示清除按钮?
Flutter Dropdown 带清除按钮实现方案
核心实现思路
- 声明可空的状态变量存储当前选中值,初始值设为
null - 重写
DropdownButton的selectedItemBuilder属性,自定义选中态的展示样式:当选中值不为空时,在展示文本末尾追加清除图标按钮 - 给清除图标绑定点击事件,点击时更新状态变量为
null即可清空选中项
完整示例代码
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Dropdown 带清除按钮示例')), body: const Padding( padding: EdgeInsets.all(20), child: CustomDropdown(), ), ), ); } } class CustomDropdown extends StatefulWidget { const CustomDropdown({super.key}); @override State<CustomDropdown> createState() => _CustomDropdownState(); } class _CustomDropdownState extends State<CustomDropdown> { // 存储选中值,可空,初始为null String? _selectedFruit; // 下拉选项列表 final List<String> _fruitList = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']; @override Widget build(BuildContext context) { return DropdownButton<String>( value: _selectedFruit, hint: const Text('请选择水果'), isExpanded: true, // 自定义选中态的展示内容 selectedItemBuilder: (BuildContext context) { return _fruitList.map((String value) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(_selectedFruit ?? ''), // 选中值不为空时展示清除按钮 if (_selectedFruit != null) InkWell( onTap: () { setState(() { _selectedFruit = null; }); }, child: const Icon(Icons.clear, size: 18, color: Colors.grey), ) ], ); }).toList(); }, // 下拉展开后的选项样式 items: _fruitList.map((String value) { return DropdownMenuItem<String>( value: value, child: Text(value), ); }).toList(), onChanged: (String? newValue) { setState(() { _selectedFruit = newValue; }); }, ); } }
注意事项
- 若需要配合表单校验使用,可以替换为
DropdownButtonFormField组件,选中态自定义逻辑完全一致 - 可以根据需求调整清除图标的样式、点击热区大小,避免和下拉框展开的点击事件冲突
- 如果需要禁止用户点击清除按钮时触发下拉框展开,可以给清除图标外层包裹
GestureDetector并设置behavior: HitTestBehavior.opaque拦截事件
内容的提问来源于stack exchange,提问作者Anoop Thiruonam
相关产品推荐
相关产品推荐

