Flutter升级至3.7.0后更新Material组件textStyle状态出现插值错误
Flutter 3.7.0升级后Material textStyle切换报错:Failed to interpolate TextStyles with different inherit values
问题原因
Flutter 3.7.0版本对TextStyle的插值逻辑新增了严格校验。当Material组件的textStyle在自定义TextStyle(默认inherit: true)和null之间切换时,会触发该错误。因为textStyle为null时,Material会使用继承自主题的默认文本样式,该样式的inherit属性与自定义TextStyle的插值逻辑冲突,导致框架无法完成样式过渡。
解决方案
方案1:用主题默认样式替代null
不要直接将textStyle设为null,而是显式使用主题中的默认文本样式,保证切换前后都是合法的TextStyle实例:
textStyle: !state ? const TextStyle(color: Color(0xff4c4c4c)) : Theme.of(context).textTheme.bodyMedium,
方案2:显式统一inherit属性
自定义TextStyle时显式指定inherit: true(和默认样式保持一致),即使切换到null也能避免插值冲突:
textStyle: !state ? const TextStyle(color: Color(0xff4c4c4c), inherit: true) : null,
方案3:将样式直接应用到子Text组件
如果业务场景允许,把样式直接设置给子Text组件,绕过Material组件的textStyle切换逻辑:
body: Material( borderRadius: const BorderRadius.all(Radius.circular(20.0)), elevation: 2, child: Text( 'Click me', style: !state ? const TextStyle(color: Color(0xff4c4c4c)) : null, ) ),
内容的提问来源于stack exchange,提问作者GNassro
相关产品推荐
相关产品推荐

