17

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(),
       );
     },
   );
 }
}
6
  • 2
    firebase.google.com/docs/flutter/setup Commented Sep 1, 2018 at 17:04
  • thanks i got this link and some more but they all just show how to retrieve the data in a ListView in new screen simply my question is how to get them in an array of strings ? Commented Sep 1, 2018 at 17:16
  • 1
    It's unclear where along the way of implementing this requirement you are stuck. Please update your question to show what you've tried already. Commented Sep 1, 2018 at 17:18
  • 1
    is your question about how to retrieve the data from firstore or about how to structure the retrieved data in your code Commented Sep 1, 2018 at 17:33
  • the question was updated it's about retrieving data in an array of string not in a listview Commented Sep 1, 2018 at 17:40

4 Answers 4

12

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

3
    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:flutter/material.dart';

    class LoadDataFromFirestore extends StatefulWidget {
      @override
      _LoadDataFromFirestoreState createState() => _LoadDataFromFirestoreState();
    }

    class _LoadDataFromFirestoreState extends State<LoadDataFromFirestore> {
      @override
      void initState() {
        super.initState();
        getDriversList().then((results) {
          setState(() {
            querySnapshot = results;
          });
        });
      }

      QuerySnapshot querySnapshot;
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: _showDrivers(),
        );
      }

    //build widget as prefered
    //i'll be using a listview.builder
      Widget _showDrivers() {
        //check if querysnapshot is null
        if (querySnapshot != null) {
          return ListView.builder(
            primary: false,
            itemCount: querySnapshot.documents.length,
            padding: EdgeInsets.all(12),
            itemBuilder: (context, i) {
              return Column(
                children: <Widget>[
//load data into widgets
                  Text("${querySnapshot.documents[i].data['activation']}"),
                  Text("${querySnapshot.documents[i].data['car1']}"),
                  Text("${querySnapshot.documents[i].data['car2']}"),
                  Text("${querySnapshot.documents[i].data['car5']}"),
                  Text("${querySnapshot.documents[i].data['name']}"),
                  Text("${querySnapshot.documents[i].data['phone']}"),
                ],
              );
            },
          );
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      }

      //get firestore instance
      getDriversList() async {
        return await Firestore.instance.collection('DriversList').getDocuments();
      }
    }

Comments

0
body: SafeArea(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        StreamBuilder(
          stream:
              FirebaseFirestore.instance.collection('messages').snapshots(),
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Center(
                child: Text(snapshot.error.toString()),
              );
            }
            if (snapshot.hasData) {
              final messages = snapshot.data!.docs;
              List<Text> messageWigdets = [];
              for (var message in messages) {
                final messageText = message['text'];
                final messageSender = message['sender'];
                final messageWigdet =
                    Text('$messageText from $messageSender');
                messageWigdets.add(messageWigdet);
              }
              return Expanded(
                child: ListView(
                  children: [...messageWigdets],
                ),
              );
            }
            return const CircularProgressIndicator.adaptive();
          },
        ),

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.