简体   繁体   中英

How to populate listview from firebase data in flutter

Hi i am trying to get data from firebase realtime database and populate listview in flutter , following is image please check before proceeding,

Here is the image from firebase Now i want to fetch data and populate listview in flutter app, currently i'm getting in terminal like this :

Data : {Reported By shivam kapasia: {Reporter Email: kapasiashivam007@gmail.com, Description: need help, Reported by: shivam kapasia, latitude: 28.4725024, Time: 5:46 PM, location: null, Date: Mon 20 Jan, longitude: 77.506273},

Here is my code:

final databaseReference = FirebaseDatabase.instance.reference();
void createRecord() {
  _getCurrentLocation();
  databaseReference.child('Reported By ' + user.displayName).set({
    'Reported by': user.displayName,
    'Reporter Email': user.email,
    'Date': formattedDate,
    'Time': res,
    'Description': '$message',
    'longitude': longitude.toString(),
    'latitude': latitude.toString(),
    'location': '$_currentAddress'
  });
}

void getData() {
  databaseReference.once().then((DataSnapshot snapshot) {
    print('Data : ${snapshot.value}');
  });
}

Both function are working fine. please help me if you know how to build listview according to data from firebase and populate them accordingly by using upper function, please try to give solution in code that will be more helpful.

Thanks in advance...

You need to create a class for all this data, your createRecord() function isn't very efficient.
Consider creating a class Report , save all the information into an object of Report .
Then, create a function within Report called toJSON() which will convert all your data to JSON format and you can directly pass it to firebase.
Similarly, you can create a named constructor called Report.fromJSON(Map snapshot) which will give you an object of Report from the snapshot you got from the database.
Now, you can create a list List<Report> reportList; containing all the reports you have fetched from firebase.
Now all you have to do is map it into a ListView as follows,

ListView(
children: reportList.map((element){return Container();}).toList(),
)


In the above example element will be an object of Report and you'll be able to display the data inside a Widget for example, a Card or a Container


If you're only looking to display one instance of Record you can manually do it by adding Widgets into the ListView ,

ListView( children: <Widget>[] )


If there's anything specific you need help with like setting up the class and the functions leave a comment, I'd be glad to help.

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