Flutter中const修饰TextStyle引发item.header常量值无效错误
解决Dart中"Invalid constant error message for item.header"错误
错误原因
你给TextStyle加了const关键字,这要求构造TextStyle时所有属性必须是编译时常量,但item.header是运行时才会确定的变量,无法作为const构造的参数,因此触发了这个错误。
修复方法
直接去掉TextStyle前面的const修饰符,让它成为一个动态创建的样式,这样就能基于item.header的值动态设置字体粗细了。
修改后的代码:
child: ListTile( key: ValueKey(item.stuffId), title: Text( item.name, style: TextStyle( // 去掉了const关键字 color: Colors.blue, fontWeight: item.header ? FontWeight.bold : FontWeight.normal, ), ), )
效果验证
修改后,列表中header为true的"Toiletries"会显示为加粗字体,其余header为false的项保持常规字体,完全符合需求。
内容的提问来源于stack exchange,提问作者fluttergogo
相关产品推荐
相关产品推荐

