Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter/Dart: How to access a single entry in a map/object

This might be a very simple question but I am having trouble finding an answer. I have a object/map that I would not like to iterate but access a specific key/value at an index.

For example:

var _results = {   'Key_1' : 'Value_1',   'Key_2' : 'Value_2',  }; 

How would I access the index[1]'s key_2 and value_2?

I've tried _results[index], _results[index].value, _results[index].key and _results[index].toString() but all returning null.

like image 871
Jesse Avatar asked Dec 18 '18 00:12

Jesse


People also ask

How do you check if a key exists in a map in Flutter?

containsKey() function in Dart is used to check if a map contains the specific key sent as a parameter. map. containsKey() returns true if the map contains that key, otherwise it returns false .


1 Answers

A map allows looking up values by keys. So:

print(_results["Key_1"]);  // prints "Value_1" 

A map is not a list of pairs, you cannot access by index.

You can access the keys, values and entries (pairs of key and value) as Iterables.

for (var key in _results.keys) print(key); // prints Key_1 then Key_2 for (var value in _results.values) print(value); // prints Value_1 then Value_2 for (var entry in _results.entries) {   print(entry.key);   print(entry.value); } 

You can even convert the entries to a list if you really want to index by integer:

var entryList = _results.entries.toList(); print(entryList[0].key);  // prints "Key_1" 

Still, this is not what maps are designed and optimized for. The map literal you wrote will iterate the entries, and their keys and values, in the order they occur in the source, but not all maps guarantee that. If you actually need a list of pairs of strings, I'd recommend making your data that from the beginning, instead of using a map. It will very likely be more efficient, and possibly easier to read.

like image 52
lrn Avatar answered Oct 08 '22 23:10

lrn