Flutter const构造器报Null不能赋值给int 传index到其他页面如何解决
报错根因
你遇到的类型赋值错误核心原因是:const修饰的构造器要求所有入参都为编译时常量,而你传入的widget.index是当前GC组件的实例动态属性,仅在运行时能确定取值,不满足const构造的参数要求,Dart的类型校验机制因此抛出异常。
解决方法
- 直接删除
DetailViewGC构造前的const修饰符即可,路由跳转的场景无需强制使用const构造实例,修改后的代码如下:
onTap: () { Navigator.push( context, MaterialPageRoute(builder: (context) => DetailViewGC( name: "Test", amount: "25€", image: AssetImage("lib/Assets/Images/test.png"), index: widget.index, ), )); },
- 如果你确实需要保留
DetailViewGC的const构造能力,可以将其定义中的index字段修改为可空类型:
class DetailViewGC extends StatefulWidget { const DetailViewGC({Key? key, required this.name, required this.amount, required this.image, this.index}) : super(key: key); final String name; final String amount; final AssetImage image; final int? index; // 其余业务代码 }
注意该方案使用index时需要做非空判断。
- 额外检查你实例化GC组件的位置,确保调用时已经给
index参数传入了有效的int值,示例:const GC(index: 1)
内容的提问来源于stack exchange,提问作者Felix Hohn
相关产品推荐
相关产品推荐

