我有一个DataSnapshot JSON对象:
{fridge2: true, fridge1: true} //data pulled from a real time firebase database
我必须把fridge2与fridge1在像这样的列表:
fridge2
fridge1
List<String> fridges;
我的尝试:
DataSnapshot fridgesDs = snapshot.value['fridges']; for (var fridge in fridgesDs) { if (fridge.value) { fridges.add(fridge.key); } }
给我这个错误:
type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Iterable<dynamic>'
我解决了 我曾经 print(fridgesDs.runtimeType);获得过Firebase返回的变量类型。它实际上是一个HashMap:_InternalLinkedHashMap<dynamic, dynamic> 将返回的值转换为 Map 。最后,我使用了forEach来遍历地图。这是最终版本:
print(fridgesDs.runtimeType);
_InternalLinkedHashMap<dynamic, dynamic>
Map<dynamic, dynamic> fridgesDs = snapshot.value['fridges']; // print(fridgesDs.runtimeType); fridgesDs.forEach((key, value) { if (value) { fridges.add(key); } });