yavg
yavg

Reputation: 3051

how can get the keys of a Map(json) in flutter?

In javascript I used

Object.keys(data["fields"]) -->  data["fields"] is a json={key1:1,key2:2...}

and returned the keys of my json. I'm looking for equivalence the flutter.

I had trying

but it doesn't seem to work

for (var field in data["fields"]) {
 print(field);

}

how can do it?

Upvotes: 0

Views: 61

Answers (2)

Richard Heap
Richard Heap

Reputation: 51750

Map has a keys getter that returns an iterator of the keys. (The default implementation of Map is a LinkedHashMap, so the order is insertion order.)

You can use that to create a list of the keys or use it as an iterator.

  var map = <int, String>{
    1: 'one',
    2: 'two',
    3: 'three',
  };
  print(map.keys.toList()); // a list of the keys
  map.keys.forEach(print); // or just use the iterator directly

Upvotes: 1

LonelyWolf
LonelyWolf

Reputation: 4402

Try this

  Map map = {"k1":"v1", "k2":"v2","k3":"v3"}; 

  map.forEach((k,v)=>print(k)); // prints k1 k2 k3

Upvotes: 2

Related Questions