Flutter路由传参异常:GalleryList模型传递后详情页获取为null
问题排查与修复方案
核心问题定位
你遇到的参数为null的直接原因是PicturesDetailView中局部变量覆盖了构造函数传入的参数,同时存在冗余的参数获取逻辑。
问题代码分析
在PicturesDetailView的build方法中,你重新定义了局部变量item,覆盖了构造函数传入的成员变量:
final GalleryList? item = ModalRoute.of(context)?.settings.arguments as GalleryList?;
虽然路由管理器已经通过构造函数正确传递了参数,但你打印和使用的是这个从ModalRoute重复获取的局部变量,而此处因路由上下文的问题导致获取失败,最终输出null。
修复步骤
1. 移除冗余参数获取逻辑,直接使用构造函数参数
修改PicturesDetailView代码,删掉build方法中重新获取参数的行,直接使用构造函数传入的item:
class PicturesDetailView extends StatelessWidget { // 将参数改为required,确保必须传入,避免空值风险 const PicturesDetailView({super.key, required this.item}); final GalleryList item; @override Widget build(BuildContext context) { print("Received argument: ${item.title}"); return Scaffold( body: SingleChildScrollView( child: BlocConsumer<HomeBloc, HomeState>( listener: (context, state) { if (state.getGalleryStatus == ScreenStatus.failure) { // 修复listener中无效的Center组件,改为提示用户 myToast( text: state.getGalleryFailures!.message, state: ToastStates.error ); } }, builder: (context, state) { if (state.getGalleryStatus == ScreenStatus.loading) { return const Center(child: CircularProgressIndicator()); } return Column( children: [ CustomAppForMedicalFile( text: 'branch'.tr(), onPressed: () => Navigator.pop(context), ), Padding( padding: EdgeInsets.all(16.0.r), child: Column( children: [ ClipRRect( borderRadius: BorderRadius.circular(12), child: Image.network( "${Constant.apiBaseUrl}/${item.img}", fit: BoxFit.fill, width: double.infinity, height: 400.h, ), ), Text(item.title ?? ''), ], ), ), ], ); }, ), ), ); } }
2. 路由管理器增加参数校验(可选)
在路由管理器中添加参数非空校验,避免传递空参数导致异常:
case RoutesName.picturesDetailView: final args = settings.arguments as GalleryList?; // 参数为空时跳转到错误页面或返回上一页 if (args == null) { return MaterialPageRoute(builder: (context) => unDefineRoute()); } return MaterialPageRoute( builder: (context) => PicturesDetailView(item: args), );
3. 确保GalleryList类的可传递性
确认GalleryList类是不可变类(所有字段为final),保证对象传递时的稳定性:
class GalleryList { final String? title; final String? img; // 其他字段同理设为final GalleryList({this.title, this.img}); // 若从JSON解析,确保fromJson方法正确实现 factory GalleryList.fromJson(Map<String, dynamic> json) { return GalleryList( title: json['title'], img: json['img'], ); } }
验证修复效果
完成上述修改后,点击PicturesView中的列表项,PicturesDetailView将正确接收并显示GalleryList实例的参数,打印日志也会输出预期的内容。
内容的提问来源于stack exchange,提问作者Icarus
相关产品推荐
相关产品推荐

