How to get Index Key of Map or List Array by Value in Flutter/Dart

In this example, we are going to show you how to get the index key of a map or list array by value in Flutter or Dart. See the two examples below where we have sown how to get the key of map by value and how to get the index of List array item by value in Dart or Flutter.

Map countries = {
  "05": "USA",
  "15": "United Kingdom",
  "22": "China",
  "27": "India",
  "35": "Brazil",
  "56": "Nepal",
  "66": "Russia"

//method 1:
var key = countries.keys.firstWhere((k)
          => countries[k] == 'Brazil', orElse: () => null);
print(key); //output: 35

//if there is no any value, the key will be null

Here, we have gone through the key of map items, and compared the value, if the value matches we return the key, if there is no matching value, we return the null.

List<String> city = ["Kathmandu", "New York", "Tokyo", "Moscow", "London"];
int index = city.indexWhere((item) => item == "Tokyo");

print(index); //output: 2

You can use list.indexWhere to get the index of the item, you have to pass the comparison on the basis you want to get the index key of the List item.

In this way, you can get the key of map or index of the List array item by its value in Dart/Flutter. You can implement these methods on your project according to your requirement. 

No any Comments on this Article

Please Wait...