Home > OS >  How to pull snapshot key & values into list through Map<>?
How to pull snapshot key & values into list through Map<>?

Time:02-08

I've been following the official Firebase tutorial for using a real-time database: https://www.youtube.com/watch?v=sXBJZD0fBa4

I am able to pull all the data from the firebase real-time database. However, the method below to do so, provides a list of the data, with no reference to the parent keys (snapshot.key). An ideal scenario would be to have a key property within the Item class (item.key), so I can call upon it directly from the list.

class DatabaseModel {

  final itemsRef = FirebaseDatabase.instance.ref().child('/Contents');

  Stream<List<Items>> getItemssStream() {

    final itemsStream = itemsRef.onValue;

    final streamToPublish = itemsStream.map((event) {

      final itemsMap = Map<String, dynamic>.from(event.snapshot.value as Map<String, dynamic>);

      final itemsList = itemsMap.entries.map((element) {
        return Items.fromRTDB(Map<String, dynamic>.from(element.value));
      }).toList();

      return itemsList;    

    });

    return streamToPublish;
  }
  
}
class Items{
  final String item;
  final String expiryDate;
  final String quantity;
  final String user;

  Items({required this.item, required this.expiryDate, required this.quantity, required this.user});

  //Mapping from real-time database
  factory Items.fromRTDB(Map<String, dynamic> data) {
    return Items(
      item: data['item'],
      expiryDate: data['exp'],
      quantity: data['qty'],
      user: data['user'],
    );
  }
  
}

CodePudding user response:

In this code you only use the element.value of each node in your results:

return Items.fromRTDB(Map<String, dynamic>.from(element.value));

If you also want to get the key of each item, you will have to also use element.key in there and pass that to your Items object.


Something like this:

Items.fromRTDB(element.key, Map<String, dynamic>.from(element.value));

...

class Items{
  final String key;
  final String item;
  final String expiryDate;
  final String quantity;
  final String user;

  Items({required this.key, required this.item, required this.expiryDate, required this.quantity, required this.user});

  //Mapping from real-time database
  factory Items.fromRTDB(String key, Map<String, dynamic> data) {
    return Items(
      key: key,
      item: data['item'],
      expiryDate: data['exp'],
      quantity: data['qty'],
      user: data['user'],
    );
  }
}
  •  Tags:  
  • Related