Flutter中如何通过setState修改ElevatedButton点击后的颜色?
问题修复方案
你的问题出在直接在setState里调用ElevatedButton.styleFrom()不会生效——这个方法只是生成一个新的样式对象,但没有关联到按钮的style属性上。要实现点击变色,需要把按钮颜色作为状态变量维护,让build方法根据变量动态生成样式。
具体修改步骤:
- 在
_MyStatefulWidgetState类中添加按钮背景色的状态变量 - 将按钮的
backgroundColor绑定到这个状态变量 - 在
onPressed的setState中更新状态变量的值
修改后的完整代码:
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: const MyStatefulWidget(), ), ); } } class MyStatefulWidget extends StatefulWidget { const MyStatefulWidget({Key? key}) : super(key: key); @override State<MyStatefulWidget> createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<MyStatefulWidget> { String frontText = "Press the Button to see studuent infomation"; // 添加按钮背景色状态变量,初始值为浅蓝 Color? buttonBgColor = Colors.lightBlue[50]; @override Widget build(BuildContext context) { return Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text( "$frontText", key: const Key("textKey"), style: const TextStyle(color: Colors.blue, fontSize: 15), ), const SizedBox(height: 20), ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: buttonBgColor, // 绑定状态变量 foregroundColor: Colors.blue, textStyle: const TextStyle(fontSize: 20) ), child: const Text('Push'), onPressed: () { setState(() { frontText = "20190952, 윤영준"; buttonBgColor = Colors.green; // 更新状态变量 }); }, ), ], ), ); } }
核心逻辑说明:
- 把按钮颜色作为State类的成员变量,这样
setState更新变量后,Flutter会重新执行build方法 - 按钮的
style属性在build时动态读取状态变量的值,从而实现颜色更新 - 不要在setState里直接生成样式对象,而是通过修改状态变量来触发UI重绘
内容的提问来源于stack exchange,提问作者백호더운
相关产品推荐
相关产品推荐

