Home > front end >  How to iterate through DataSnapshot from Firebase Realtime Database in Flutter
How to iterate through DataSnapshot from Firebase Realtime Database in Flutter

Time:11-18

I have the following data in Firebase:

First Screenshot

When I try to read all the children of 'hospitals' using get(), an InternalLinkedHashMap<Object?, Object?> is being returned:

Second Screenshot

I need to iterate through the returned value and get all the lat and long of the three children and put it in a List<Hospitals>, which has Name, Phone, Lat and Long as its properties, and later plot these coordinates in a Map. I am not able to iterate through the InternalLinkedHashMap<Object?, Object?>.

Please help to figure out the iteration?

Code I have tried -

fetchMarkers() async {
  nHospitals.clear();
  final snapshot = await dbRef.child('information/hospitals').get();
  if (snapshot.exists) {
    print(snapshot.value);
  }
}

I also tried the following, but the same issue: I am not able to iterate through the InternalLinkedHashMap<Object?, Object?>.

ref.onValue.listen((event) {
  for (final child in event.snapshot.children) {
    //A list of children is returned
    //print(child);
  }
}, one rror: (error) {
  //Handle the error
});

This is Hospitals class

import 'package:json_annotation/json_annotation.dart';

part 'hospitals.g.dart';

@JsonSerializable()
class Hospitals {
  final String lat;
  final String lng;
  final String name;
  final String phone;

  Hospitals(
      {required this.lat,
      required this.lng,
      required this.name,
      required this.phone});

  factory Hospitals.fromJson(Map<String, dynamic> json) =>
      _$HospitalsFromJson(json);

  Map<String, dynamic> toJson() => _$HospitalsToJson(this);
}

CodePudding user response:

The result of a get() call is a DataSnapshot object, which has a children property that has all the child snapshots. That's what you do in the second code snippet, and it looks fine to me.

If you then want to get a child property of that snapshot, you can call child("lat").value.

ref.get().then((snapshot) {
  for (final hospital in snapshot.children) {
    print(hospital.child("lat").value);
  }
}, one rror: (error) {
  ..
});
  • Related