You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter开发:无法修改TextButton背景色及文本颜色问题求助

解决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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 07:10:33