无法在DART中的地图列表中使用indexOf [英] Can't use indexOf in List of Map in DART

查看:41
本文介绍了无法在DART中的地图列表中使用indexOf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的地图列表

I have a List of Map like this

List<Map<String, String>> data = [
  {"id":"1", "name":"Job"},
  {"id":"2", "name":"Teh"},
  {"id":"3", "name":"Maru"},
  {"id":"4", "name":"Pam"},
];

void main() {
  var index = data.indexOf({"id":"1", "name":"Job"});
  print("Index: $index");
}

在DartPad上运行的结果是:索引:-1.如何在列表中的Map对象中使用indexOf?谢谢

Result run on DartPad was: Index: -1. How can I using indexOf for Map object in List? Thanks

推荐答案

它不起作用,因为两个映射不是同一对象,要解决此问题,您可以使用const对象或使用 indexWhere

It doesn't work because the two maps aren't the same Object, to solve that, you can either use const objects or use indexWhere

使用const:

// Create a const (immutable) list.
List<Map<String, String>> data = const [
  {"id":"1", "name":"Job"},
  {"id":"2", "name":"Teh"},
  {"id":"3", "name":"Maru"},
  {"id":"4", "name":"Pam"},
];

void main() {
  // Search for the map.
  var index = data.indexOf(const {"id":"1", "name":"Job"});
  print("Index: $index");
}

使用索引位置:

List<Map<String, String>> data = const [
  {"id":"1", "name":"Job"},
  {"id":"2", "name":"Teh"},
  {"id":"3", "name":"Maru"},
  {"id":"4", "name":"Pam"},
];

void main() {
  // Index where id is 1 and name is Job.
  var index = data.indexWhere((e) => e["id"] == "1" && e["name"] == "Job");
  print("Index: $index");
}

这篇关于无法在DART中的地图列表中使用indexOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆