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

Flutter中如何在Widget中正确使用参数?解决常量值错误

解决Flutter中StatefulWidget传参到ModelViewer的「Invalid constant value」错误

错误原因

这个错误的核心是:你大概率给ModelViewer加了const关键字声明,但widget.srcURL是StatefulWidget的实例参数,属于运行时动态确定的值,不能作为常量传递给const构造函数。

正确实现代码

// 自定义的StatefulWidget,接收srcURL参数
class Viewer extends StatefulWidget {
  final String srcURL;

  // 这里的const没问题,因为srcURL是final,由父组件传入时确定
  const Viewer({super.key, required this.srcURL});

  @override
  State<Viewer> createState() => _ViewerState();
}

class _ViewerState extends State<Viewer> {
  @override
  Widget build(BuildContext context) {
    // 关键:去掉ModelViewer前面的const关键字
    return ModelViewer(
      src: widget.srcURL, // 直接使用widget.srcURL即可
      // 其他配置属性按需添加,比如width、height等
    );
  }
}

关键注意点

  • 不要给需要动态传参的ModelViewer加const,因为const要求所有参数都是编译时常量,而widget.srcURL是父组件传入的动态值,不符合常量要求。
  • 如果你的ModelViewer构造函数本身是const构造,那它只接受常量值;但你需要动态传入srcURL的场景下,必须放弃使用const来创建ModelViewer实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:03:14