Param B.
Param B.

Reputation: 95

How to convert Firestore document data into a Class

In Firestore, theres some documents with fields like 'name' , 'continent' etc with their string values. Im using FutureBuilder in the main UI code, and calling the getData() function.

Here's my code

class DatabaseService {

  final locationCollection = FirebaseFirestore.instance.collection("location");

  Future<List<HomePageModel>> getData() async {

    List<HomePageModel> listData = [];

    await locationCollection.get().then((QuerySnapshot querySnapshot){
      querySnapshot.docs.forEach((doc) {
        HomePageModel(
          docId: doc.id,
          continent: doc['continent'],
          name: doc['name']
        );
      });
    });
    print("this is listData $listData");
    return listData;
  }

}

This is what console looks like:

I/flutter ( 430): this is listData []

And this is the HomePageModel class

class HomePageModel {

  String? name;
  String? docId;
  String? continent;
  HomePageModel({this.docId, this.name, this.continent});
}

I dont know how do i put these document data models retrieved from Firestore in listData thats why in the console listData doesnt have any data. Thank you :)

Upvotes: 2

Views: 1599

Answers (1)

Ferenc Orosi
Ferenc Orosi

Reputation: 265

Param B.

I think the problem is here.

    await locationCollection.get().then((QuerySnapshot querySnapshot){
      querySnapshot.docs.forEach((doc) {
        HomePageModel(
          docId: doc.id,
          continent: doc['continent'],
          name: doc['name']
        );
      });
    });

The first issue is you did not make a new object instance. The second is you did not add your new object instance to the list.

I did not test the code, but i think this is going to work.

class DatabaseService {

  final locationCollection = FirebaseFirestore.instance.collection("location");

  Future<List<HomePageModel>> getData() async {

    List<HomePageModel> listData = [];

    await locationCollection.get().then((QuerySnapshot querySnapshot){
      querySnapshot.docs.forEach((doc) {
        HomePageModel homepagemodel = new HomePageModel( // the first issue
          docId: doc.id,
          continent: doc['continent'],
          name: doc['name']
        );
        listData.add(homepagemodel); // the second issue
      });
    });
    return listData;
  }

}

One more thing. I do not really know what is the difference between using { } and ? in a class, but i have never used it. I make a class like this. But i think your class also works.

class HomePageModel {
  String name;
  String docId;
  String continent;
  
  HomePageModel(this.docId, this.name, this.continent);
}

One more thing, print is not going to work for a list of items. You need to use for example a for loop like this.

for (var i = 0; i < listData.length; i++) {
   print("Loaded data: " + listData[i].name);
}

Upvotes: 3

Related Questions