Flutter Xylophone项目中FloatingActionButton传入背景色不生效如何解决
问题根源
你在buildKey方法中定义的backgroundColors参数没有绑定到FloatingActionButton的背景色属性上,按钮默认使用主题色,结合黑色的Scaffold背景就会出现全黑的显示效果。
修复代码
直接替换你的buildKey方法即可修复颜色不显示的问题:
Expanded buildKey({required int n, required Color backgroundColor}) { return Expanded( child: FloatingActionButton( onPressed: () { final player = AudioCache(); player.play('note$n.wav'); }, shape: RoundedRectangleBorder(), // 新增这行绑定传入的颜色 backgroundColor: backgroundColor, elevation: 0, ), ); }
同时修改调用处的参数名,和修改后的参数对应:
children: <Widget>[ buildKey(n: 1, backgroundColor: Colors.red), buildKey(n: 2, backgroundColor: Colors.orange), buildKey(n: 3, backgroundColor: Colors.yellow), buildKey(n: 4, backgroundColor: Colors.green), buildKey(n: 5, backgroundColor: Colors.teal), buildKey(n: 6, backgroundColor: Colors.blue), buildKey(n: 7, backgroundColor: Colors.purple), ]
更简洁的实现方式
不用手动写7次buildKey调用,用列表批量生成即可:
@override Widget build(BuildContext context) { final keyColors = [ Colors.red, Colors.orange, Colors.yellow, Colors.green, Colors.teal, Colors.blue, Colors.purple ]; return MaterialApp( home: Scaffold( backgroundColor: Colors.black, body: SafeArea( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: List.generate(7, (index) => buildKey( n: index + 1, backgroundColor: keyColors[index] )), ), ), ), ); }
内容的提问来源于stack exchange,提问作者Edgar Torres
相关产品推荐
相关产品推荐

