How to deal with object from Firebase Realtime Database in Flutter

Issue

I am having trouble dealing with object type in realtime database in firebase. I want to convert it into json format. I searched but found none regarding this topic. To be clearer, I am using onValue to listen for this object like this:

currentRef.onValue.listen((event) {
  setState(() {
    currentReading = event.snapshot.value.toString();
  });

But I don’t need to convert it to String, I want to deal with data within this Object.

Data printed:

{
"2022 11 21": 400,
  "2022 11 22": 232,
  "2022 11 23": 500
}

Data Type: IdentityMap<String, dynamic>

Solution

You can get your specific data this way:

currentRef.onValue.listen((event) {
  String yourSpecificDate = "2022 11 21";
  var result = Map.fromEntries(
        event.entries.where((element) => element.key == yourSpecificDate));

  print("result = $result");//result = {2022 11 21: 223}
  print("value = ${result.entries.first.value}");//value = 223
});

Answered By – eamirho3ein

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *