Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

can't fetch data into a list in flutter using firebase

I’m trying to fetch data from firebase cloud firestore in flutter, but i’m struggling to save it into a specific list.

Here is my code:

Future<List<Intervention>> fetchInterventions() async {
      List<Intervention> ivs = [];
      final doc =
          await FirebaseFirestore.instance.collection('interventions').get();
      final interventionsTmp = doc.data();
      interventionsTmp .forEach((interventionTmp ) {
        ivs.add(Intervention.fromJson(interventionTmp ));
      });
      return ivs;
    }

and here is my model:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Intervention {
  final String intervention;
  final String dateIv;
  final String etat;
  final int prix;
  final String numero;

  Intervention(
      {required this.dateIv,
      required this.etat,
      required this.numero,
      required this.intervention,
      required this.prix});

  static Intervention fromJson(Map<String, dynamic> map) {
    return Intervention(
        dateIv: map['date_iv'],
        etat: map['etat'],
        intervention: map['intervention'],
        numero: map['numIntervention'],
        prix: map['prix']);
  }
}

For now the problem is that I cannot access the data in this line final interventionsTmp = doc.data(); since data() isn’t a known method for it! I’m stuck at accessing the data.

I tried several solutions but couldn’t solve it, I’d be glad with any kind of help.

>Solution :

Change your fetchInterventions to this:

Future<List<Intervention>> fetchInterventions() async {
  QuerySnapshot querySnapshot =
      await FirebaseFirestore.instance.collection('interventions').get();
  
  
  return querySnapshot.docs.map((doc) => Intervention.fromJson(doc.data() as Map<String, dynamic>)).toList();;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading