Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a Firebase datasnapshot sub childrens? Flutter

I have a DataSnapshot JSON object :

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

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

List<String> fridges;

My attempt:

DataSnapshot fridgesDs = snapshot.value['fridges'];

    for (var fridge in fridgesDs) {
      if (fridge.value) {
        fridges.add(fridge.key);
      }
    }

Gives me this error:

type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Iterable<dynamic>'
like image 941
TSR Avatar asked Aug 05 '18 17:08

TSR


1 Answers

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);
      }
    });
like image 159
TSR Avatar answered Oct 18 '22 06:10

TSR