Flutter中如何获取复杂列表内指定timestamp对应元素的索引
需求说明
现有如下结构的嵌套列表:
List messages = [ [ { body: "QGB59WIO57 Confirmed. Your account balance was: M-PESA Account : Ksh0.00 on 11/7/22 at 12:42 PM. Transaction cost, Ksh0.00. Dial *334# now to get your stamped M-Pesa Statement.", address: "MPESA", timestamp: 1657532523000, status: "failed" } ], [ { body: "QGB7A3UGAX Confirmed. Your account balance was: M-PESA Account : Ksh0.00 on 11/7/22 at 2:18 PM. Transaction cost, Ksh0.00. Dial *334# now to get your stamped M-Pesa Statement.", address: "MPESA", timestamp: 1657538312000, status: "failed" } ] ];
需要查找列表中timestamp字段值等于1657538312000的元素,返回其在最外层列表对应的索引,示例中匹配项为外层列表的第二个元素。
实现方法
该列表为两层嵌套结构:最外层每个元素是一个子列表,子列表内部才是存储timestamp字段的键值对对象,直接遍历最外层列表做值匹配即可,以下是适配Dart语法(从列表定义规则判断为Dart/Flutter场景)的实现代码:
- 基础for循环实现:逻辑直观,方便扩展自定义判断规则
const targetTimestamp = 1657538312000; int? matchIndex; for (int i = 0; i < messages.length; i++) { // 取当前索引对应子列表的首个对象,匹配timestamp字段 if (messages[i][0]['timestamp'] == targetTimestamp) { matchIndex = i; break; // 找到匹配项后立刻终止遍历,减少冗余计算 } }
运行后matchIndex返回值为1,对应外层列表第二个元素(常规编程语言列表索引均从0开始计数)。
- indexWhere简写实现:代码更精简,适合简单匹配场景
const targetTimestamp = 1657538312000; int matchIndex = messages.indexWhere((subList) => subList[0]['timestamp'] == targetTimestamp);
注意:如果列表中不存在匹配目标时间戳的元素,
indexWhere会返回-1,实际业务使用时建议增加判断逻辑做兼容处理。
内容的提问来源于stack exchange,提问作者KEVIN
相关产品推荐
相关产品推荐

