Flutter如何从模型类列表中获取Navigator传参ID匹配的指定项
实现方法
- 首先为
DetailsPage补充构造函数,接收你跳转时传入的ID参数 - 之后调用
place列表的firstWhere方法,筛选出ID与传入值匹配的Place对象即可
完整示例代码
import 'package:flutter/material.dart'; // 如果Place类和place列表定义在其他文件,需要在此处导入对应文件,同文件可忽略该步骤 // import '你存放Place定义的文件路径.dart'; class DetailsPage extends StatelessWidget { // 存储跳转传入的地点ID final int placeId; // 构造函数接收ID参数 const DetailsPage(this.placeId, {super.key}); @override Widget build(BuildContext context) { // 筛选ID匹配的Place对象 Place targetPlace = place.firstWhere((item) => item.id == placeId); // 可选:添加异常处理,避免传入的ID不存在时程序崩溃 // Place targetPlace = place.firstWhere( // (item) => item.id == placeId, // orElse: () => Place( // id: 0, // cardImage: '', // placeName: '该地点不存在', // location: '', // country: '', // details: '', // ), // ); return Scaffold( appBar: AppBar(title: Text(targetPlace.placeName)), body: ListView( children: [ Image.network(targetPlace.cardImage), Padding( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( targetPlace.placeName, style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold), ), const SizedBox(height: 8), Text( '${targetPlace.location}, ${targetPlace.country}', style: const TextStyle(fontSize: 16, color: Colors.grey), ), const SizedBox(height: 16), Text(targetPlace.details), ], ), ) ], ), ); } }
说明
firstWhere方法会遍历整个place列表,返回第一个满足item.id == placeId判断条件的元素,正好匹配你根据ID取对应项的需求。
内容的提问来源于stack exchange,提问作者Utpal Mandal
相关产品推荐
相关产品推荐

