Flutter:如何为myui函数传递backgroundColor参数?
要实现通过myui函数传递参数来控制TextButton的背景色,只需按以下步骤修改代码:
- 为
myui函数添加Color类型的参数(推荐用命名参数,可读性更强) - 将
TextButton.styleFrom里固定的Colors.red替换为传入的参数 - 调用函数时传入目标颜色值即可
修改后的完整代码
Expanded myui({required Color buttonColor}) { return Expanded( child: TextButton( onPressed: () { audio(1); }, style: TextButton.styleFrom(backgroundColor: buttonColor), child: const Text(""), ), ); }
调用示例
// 设置背景色为蓝色 myui(buttonColor: Colors.blue) // 使用自定义ARGB颜色 myui(buttonColor: Color.fromARGB(255, 80, 160, 220))
可选:添加默认颜色
如果希望不传参数时保持原有的红色背景,可以给参数设置默认值:
Expanded myui({Color buttonColor = Colors.red}) { // 内部实现和上面一致 }
内容的提问来源于stack exchange,提问作者manape
相关产品推荐
相关产品推荐

