Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get data from firebase in flutter

I am building a flutter app and using cloud-firestore, this is how my database looks like enter image description here

I want a function that retrieves all documents in the collection called "Driver List" in an array of strings that what I had already used but it gets them back in a listview in a new screen

class DriverList extends StatelessWidget {@overrideWidget build(BuildContext context) {
return new StreamBuilder<QuerySnapshot>(
  stream: Firestore.instance.collection('DriverList').snapshots(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (!snapshot.hasData) return new Text('Loading...');
    return new ListView(
      children: snapshot.data.documents.map((DocumentSnapshot document) {
        return new ListTile(
          title: new Text(document['name']),
          subtitle: new Text(document['phone']),
        );
      }).toList(),
    );
  },
);

} }

like image 928
Ahmed El Sayed Avatar asked Sep 01 '18 16:09

Ahmed El Sayed


People also ask

How do I get data from Firebase?

Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.


1 Answers

  • 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());
      },
    )
    
like image 114
CopsOnRoad Avatar answered Oct 06 '22 16:10

CopsOnRoad