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
相关产品推荐
相关产品推荐

