简体   繁体   中英

How to iterate through DataSnapshot from Firebase Realtime Database in Flutter

I have the following data in Firebase:

第一张截图

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

第二个截图

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);
  }
}, onError: (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);
}

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);
  }
}, onError: (error) {
  ..
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM