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

Time:12-27

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:

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.

CodePudding user response:

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();;
}
  • Related