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

Flutter ElevatedButton背景色Widget测试值一致仍报错如何解决

问题原因

MaterialStateProperty.all() 返回的是 _MaterialStatePropertyAll 私有类实例,该类没有重载 == 运算符和 hashCode,因此即使两个实例包裹的颜色值完全一致,只要是不同的实例对象,直接做相等判断就会返回false,触发断言失败。日志输出的是实例的字符串格式化结果,所以视觉上看起来预期值和实际值完全相同。

解决方法

不要直接对比 MaterialStateProperty 实例,而是调用其 resolve 方法获取指定状态下的实际颜色值后再做断言。
将原断言代码替换为以下实现即可:

final targetButton = tester.firstWidget(find.byType(ElevatedButton)) as ElevatedButton;
// 传入空状态集合获取默认状态下的背景色值
final actualBackgroundColor = targetButton.style?.backgroundColor?.resolve({});
expect(actualBackgroundColor, AppColors.button_disabled);

补充说明

如果需要验证其他交互状态下的颜色(如禁用、按下、悬停),只需给 resolve 方法传入对应的状态集合即可,比如验证禁用状态颜色可写为:

final disabledBgColor = targetButton.style?.backgroundColor?.resolve({MaterialState.disabled});

内容的提问来源于stack exchange,提问作者pAr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:36:03