基于Material State的ElevatedButton悬停文本样式未生效
问题出在ElevatedButton的文本颜色由foregroundColor属性控制,你之前在textStyle里设置的color会被foregroundColor覆盖,所以悬停时文本颜色不会变化。
修正后的代码
ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.hovered)) { return Colors.green; } // 补充默认背景色,避免未悬停时背景透明 return Theme.of(context).colorScheme.primary; }), // 用foregroundColor控制文本颜色的状态切换 foregroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { return states.contains(MaterialState.hovered) ? Colors.blue : Colors.white; }), // textStyle仅负责字体样式(粗细、大小等),不用设置颜色 textStyle: MaterialStateProperty.all( const TextStyle(fontWeight: FontWeight.w600), ), ), onPressed: () {}, child: const Text('hello'), );
关键说明
foregroundColor是Flutter按钮组件中专门控制前景元素(文本、图标)颜色的属性,支持根据MaterialState(悬停、按下、禁用等)切换颜色,优先级高于textStyle中的color设置- 之前的代码里要注意给
backgroundColor补充默认返回值,否则未悬停状态下按钮背景会变成透明
内容的提问来源于stack exchange,提问作者krishnaji
相关产品推荐
相关产品推荐

