Home > other >  How to dynamically read specific data from firebase realtime database using flutter
How to dynamically read specific data from firebase realtime database using flutter

Time:08-09

I am struggling to reference specific things in my firebase real time database. I understand that when you want to read something specific from the database you need to specify the exact path where the item can be found.

If you see the screenshot attached, I want a way to read the name of each menuItem and store them in a list.

It seems like this can only be done if you reference each menuItem ID individually in the path (like in the code below).

Is there not a way to say ("menuItem/itemID/itemName") so that I can access each menuItem name dynamically using a for loop with a terminating value equal to the number of menu items in the database?

Any help would be greatly appreciated!

enter image description here


final DatabaseReference _dbRef = FirebaseDatabase.instance.ref();
  late DataSnapshot _itemStream;[![enter image description here][1]][1]


Future<List<String>> _readItemNames() async {
    
      _itemStream = await _dbRef.child("menuItem/J1/itemName").get();
      itemName = _itemStream.value.toString();
      itemNames.addAll([itemName]);
      
      _itemStream = await _dbRef.child("menuItem/J2/itemName").get();
      itemName = _itemStream.value.toString();
      itemNames.addAll([itemName]);

    
    return itemNames;
  }

CodePudding user response:

If you want to read and process all menu items, you can do:

var snapshot = await _dbRef.child("menuItem").get();
snapshot.children.forEach((childSnapshot) {
  var props = childSnapshot.val() as Map;
  print(props["itemName"]);
}); 

For more on this, see the Firebase documentation on reading a list of items with a value event (you're just using get() instead of onValue, but the logic is the same).


There is no way to get only the itemName property of each child node, so if all you need it the names you're loading more data than needed. If that is a concern, consider creating an additional list with just the value(s) you need. For example:

menuItemNames: {
  "J1": "Milk Shake",
  "J10": "Name of J10",
  ...
}
  • Related