how to get data from firebase in flutter
Asked Answered
C

4

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(),
       );
     },
   );
 }
}
Carilyn answered 1/9, 2018 at 16:52 Comment(6)
firebase.google.com/docs/flutter/setupOverland
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 ?Carilyn
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.Philibeg
is your question about how to retrieve the data from firstore or about how to structure the retrieved data in your codeRoryros
the question was updated it's about retrieving data in an array of string not in a listviewCarilyn
Does this answer your question? how to read data from firestore flutterPlaylet
M
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

Mensal answered 1/9, 2018 at 19:41 Comment(0)
R
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());
      },
    )
    
Redfield answered 6/6, 2021 at 15:26 Comment(0)
V
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();
      }
    }
Virgil answered 17/8, 2019 at 10:21 Comment(0)
R
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();
          },
        ),
Revet answered 6/10, 2022 at 12:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.