how to get data from firebase in flutter

This has some additional logic to remove potentially duplicate records, but you can use something like the following to retrieve data from Firestore.

We get access to a collection reference, then list the results of the query, then create local model objects for the data returned by Firestore, and then we return the a list of those model objects.

  static Future<List<AustinFeedsMeEvent>> _getEventsFromFirestore() async {
CollectionReference ref = Firestore.instance.collection('events');
QuerySnapshot eventsQuery = await ref
    .where("time", isGreaterThan: new DateTime.now().millisecondsSinceEpoch)
    .where("food", isEqualTo: true)
    .getDocuments();

HashMap<String, AustinFeedsMeEvent> eventsHashMap = new HashMap<String, AustinFeedsMeEvent>();

eventsQuery.documents.forEach((document) {
  eventsHashMap.putIfAbsent(document['id'], () => new AustinFeedsMeEvent(
      name: document['name'],
      time: document['time'],
      description: document['description'],
      url: document['event_url'],
      photoUrl: _getEventPhotoUrl(document['group']),
      latLng: _getLatLng(document)));
});

return eventsHashMap.values.toList();
}

Source: https://github.com/dazza5000/austin-feeds-me-flutter/blob/master/lib/data/events_repository.dart#L33


  • Getting one time data:

    var collection = FirebaseFirestore.instance.collection('DriverList');
    var querySnapshot = await collection.get();
    for (var queryDocumentSnapshot in querySnapshot.docs) {
      Map<String, dynamic> data = queryDocumentSnapshot.data();
      var name = data['name'];
      var phone = data['phone'];
    }
    
  • Getting data each time it changes, using a StreamBuilder:

    StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
      stream: FirebaseFirestore.instance.collection('DriverList').snapshots(),
      builder: (_, snapshot) {
        if (snapshot.hasError) return Text('Error = ${snapshot.error}');
    
        if (snapshot.hasData) {
          final docs = snapshot.data!.docs;
          return ListView.builder(
            itemCount: docs.length,
            itemBuilder: (_, i) {
              final data = docs[i].data();
              return ListTile(
                title: Text(data['name']),
                subtitle: Text(data['phone']),
              );
            },
          );
        }
    
        return Center(child: CircularProgressIndicator());
      },
    )