Flutter开发中如何实现点击黄色圆形控件后弹出自定义颜色选择对话框?
实现方案
以下是针对需求的具体修改步骤,无需引入第三方依赖即可实现对应效果:
第一步:新增状态变量
在_NewCounterState类中新增两个状态变量,用于存储可选颜色列表和当前选中的颜色:
class _NewCounterState extends State<NewCounter> { final FocusNode textNode = FocusNode(); final FocusNode numberNode = FocusNode(); TextStyle labelStyle; TextStyle numberStyle; // 新增内容开始 List<Color> availableColors = [ Colors.yellow, Colors.red, Colors.blue, Colors.green, Colors.orange, Colors.purple, Colors.pink, Colors.cyan, ]; Color selectedColor = kMainColor; // 新增内容结束 // 原有initState等代码不变 ... }
第二步:实现颜色选择对话框方法
在_NewCounterState类中新增对话框调用方法:
void showColorPickerDialog() { showDialog( context: context, builder: (context) => AlertDialog( title: const Text("选择颜色"), content: GridView.count( shrinkWrap: true, crossAxisCount: 4, crossAxisSpacing: 12, mainAxisSpacing: 12, children: availableColors.map((color) { return GestureDetector( onTap: () { setState(() { selectedColor = color; }); Navigator.pop(context); }, child: Container( decoration: BoxDecoration( color: color, shape: BoxShape.circle, border: selectedColor == color ? Border.all(color: Colors.black, width: 2) : null, boxShadow: const [ BoxShadow(color: Colors.black26, blurRadius: 2, spreadRadius: 1) ] ), ), ); }).toList(), ), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text("取消") ) ], ), ); }
第三步:修改原有绑定逻辑
- 把原有代码中所有直接引用
kMainColor的位置替换为selectedColor,包括AppBar背景色、输入框光标颜色、选中边框颜色等,保证选中颜色全局生效。 - 修改颜色选择圆形按钮的点击事件和背景色绑定:
// 原有圆形按钮代码修改后如下 Container( decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.black, boxShadow: [ BoxShadow( color: Colors.black54, spreadRadius: 2, blurRadius: 2, ), ], ), child: RaisedButton( child: Padding( padding: EdgeInsets.all(40.0), ), onPressed: showColorPickerDialog, // 绑定对话框调用 shape: CircleBorder(), color: selectedColor, // 绑定选中的颜色 ), ),
可选优化
RaisedButton在Flutter 2.0之后已被弃用,你可以替换为更新的ElevatedButton组件,写法如下:
ElevatedButton( style: ElevatedButton.styleFrom( shape: const CircleBorder(), padding: const EdgeInsets.all(40), backgroundColor: selectedColor, ), onPressed: showColorPickerDialog, child: const SizedBox(), )
内容的提问来源于stack exchange,提问作者Ahmed Loutfy
相关产品推荐
相关产品推荐

