Ahmed El Sayed
Ahmed El Sayed

Reputation: 519

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

Upvotes: 17

Views: 74474

Answers (4)

darlingtonhp
darlingtonhp

Reputation: 1

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

Upvotes: 0

CopsOnRoad
CopsOnRoad

Reputation: 267384

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

Upvotes: 8

dazza5000
dazza5000

Reputation: 7608

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

Upvotes: 12

griffins
griffins

Reputation: 8246

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

Upvotes: 3

Related Questions