如何遍历Firebase datasnapshot子项?扑

如何遍历Firebase datasnapshot子项?扑

问题描述:

我有一个DataSnapshot JSON对象:

I have a DataSnapshot JSON object :

{fridge2: true, fridge1: true} //data pulled from a real time firebase database

我必须放入 fridge2 fridge1 在这样的列表中:

I have to put fridge2 and fridge1 in a list like this:

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遍历了地图。这是最终版本:

I solved it. I used to print(fridgesDs.runtimeType); to get the type of variable returned by firebase. it is actually a HashMap: _InternalLinkedHashMap<dynamic, dynamic> The casted the returned value into a Map. Finally, I used forEach to loop through the map. Here is the final version:

 Map<dynamic, dynamic> fridgesDs = snapshot.value['fridges'];
//    print(fridgesDs.runtimeType);
    fridgesDs.forEach((key, value) {
      if (value) {
        fridges.add(key);
      }
    });