这可能是一个非常简单的问题,但我很难找到答案。 我有一个对象/映射,我不想迭代但访问索引处的特定键/值。
例如:
var _results = {
'Key_1' : 'Value_1',
'Key_2' : 'Value_2',
};
如何访问索引[1] 的 key_2 和 value_2?
我试过 _results[index]
、_results[index].value
、_results[index].key
和 _results[index].toString()
但都返回 null。
最佳答案
map 允许通过键查找值。所以:
print(_results["Key_1"]); // prints "Value_1"
map 不是对的列表,您不能通过索引访问。
您可以以Iterable
s的形式访问键、值和条目(键和值对)。
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);
}
如果您真的想按整数索引,您甚至可以将条目转换为列表:
var entryList = _results.entries.toList();
print(entryList[0].key); // prints "Key_1"
不过,这并不是 map 的设计和优化目的。您编写的映射文字将按照它们在源中出现的顺序迭代条目及其键和值,但并非所有映射都保证这一点。如果您确实需要成对的字符串列表,我建议您从一开始就制作数据,而不是使用 map 。它很可能会更有效,并且可能更易于阅读。
关于dictionary - flutter/Dart : How to access a single entry in a map/object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53824755/