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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:44:54