Flutter中如何跨类、跨页面访问已定义的Map对象?
跨类传递Map数据实现方案
改造目标页面records_page.dart接收参数
首先修改RecordsPage类,增加Map参数的接收逻辑,同时把Map转成可索引的列表适配ListView.builder:
// records_page.dart 核心代码 class RecordsPage extends StatelessWidget { // 声明要复用的Map成员变量 final Map<String, dynamic> records; // 构造函数强制要求传入Map参数 const RecordsPage({super.key, required this.records}); @override Widget build(BuildContext context) { // 将Map键值对转为可索引的列表,保留原有插入顺序 final recordList = records.entries.toList(); return Scaffold( appBar: AppBar(title: const Text('记录列表')), // 空列表时显示占位提示 body: recordList.isEmpty ? const Center(child: Text('暂无记录数据')) : ListView.builder( itemCount: recordList.length, itemBuilder: (context, index) { final currentItem = recordList[index]; // 生成对应键值对的展示卡片 return Card( margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), child: ListTile( title: Text(currentItem.key), subtitle: Text(currentItem.value.toString()), ), ); }, ), ); } }
在show_page.dart跳转时传递Map
在ShowPage类的跳转逻辑中,直接把生成好的records对象作为参数传入RecordsPage的构造函数即可:
// show_page.dart 跳转逻辑示例(比如按钮点击触发) onPressed: () { Navigator.push( context, MaterialPageRoute( // 传入当前类内生成的records Map builder: (context) => RecordsPage(records: records), ), ); },
补充说明
- 该方案属于页面构造传参,仅适合单向数据传递场景(当前页面展示Map数据),无需引入额外状态管理依赖。
- 如果后续需要双向同步Map数据(比如在
RecordsPage修改Map后同步回ShowPage),可改用全局状态管理工具或回调传值的方式实现。
内容的提问来源于stack exchange,提问作者user14217653
相关产品推荐
相关产品推荐

