Flutter路由传参问题:接收页无法访问传递对象的属性
问题描述
我通过路由传递包含title、description、id的歌曲数据对象,跳转代码如下:
onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => SongScreen(), settings: RouteSettings( arguments: item.data![index], ), ), ); },
在接收页面SongScreen中,通过final song = ModalRoute.of(context)!.settings.arguments;获取对象后,尝试用Text('${song.title}')访问属性时报错。打印显示获取到的对象是:
{ title: 'abc', id: 32 }
只能拿到对象本身,无法直接访问内部属性。
解决方案
方案1:直接转为Map类型访问
你传递的实际是Map<String, dynamic>类型的对象,Dart无法自动推断其类型,需要先强制转换,再通过键值对方式访问属性:
// 在SongScreen中 final song = ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>; // 访问属性 Text('${song['title']}'), Text('${song['id']}'), // 处理可选的description字段(避免空值报错) Text('${song['description'] ?? '暂无简介'}'),
方案2:定义自定义Song模型类(推荐)
如果项目中频繁使用歌曲数据,定义模型类可以获得类型检查支持,还能通过.语法直接访问属性:
- 先定义Song类:
class Song { final String title; final String? description; // 可选字段设为可空类型 final int id; Song({ required this.title, this.description, required this.id, }); // 从Map转换为Song实例的工厂方法 factory Song.fromMap(Map<String, dynamic> map) { return Song( title: map['title'] as String, description: map['description'] as String?, id: map['id'] as int, ); } }
- 跳转时将Map转为Song实例再传递:
onTap: () { final song = Song.fromMap(item.data![index]); Navigator.push( context, MaterialPageRoute( builder: (context) => SongScreen(), settings: RouteSettings( arguments: song, ), ), ); },
- 在SongScreen中接收并转换类型:
final song = ModalRoute.of(context)!.settings.arguments as Song; // 直接用点语法访问属性 Text(song.title), Text('${song.id}'), Text(song.description ?? '暂无简介'),
内容的提问来源于stack exchange,提问作者HARSH J.
相关产品推荐
相关产品推荐

