Flutter开发:无法修改TextButton背景色及文本颜色问题求助
问题根源
你把TextButton.styleFrom()写在了onPressed回调函数内部,这个位置的代码只会在按钮点击时执行,完全不会作用于按钮的样式配置。按钮的样式需要直接作为TextButton的style参数传入。
修正后的代码
import 'package:flutter/material.dart'; import 'package:audioplayers/audioplayers.dart'; void main() => runApp(const CustomXylophoneApp()); class CustomXylophoneApp extends StatelessWidget { const CustomXylophoneApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: SafeArea( child: Column( children: <Widget>[ TextButton( // 将样式配置移至此处,作为style参数传入 style: TextButton.styleFrom( backgroundColor: Colors.blue, foregroundColor: Colors.red, ), onPressed: () { AudioCache player = AudioCache(); player.play('assets_note1.wav'); }, child: const Text('Tune1'), ), ], ), ), ), ); } }
补充说明
styleFrom是TextButton提供的快捷样式配置方法,直接设置backgroundColor(背景色)和foregroundColor(文本、图标颜色)即可生效。- 如果需要更复杂的样式定制,可以使用
ButtonStyle类,比如设置圆角、边框、阴影等。
内容的提问来源于stack exchange,提问作者Jishnu Vijayan
相关产品推荐
相关产品推荐

