Created
December 8, 2019 17:42
-
-
Save r3dm1ke/4a4b7b972645ea45738bacbb0d966ac8 to your computer and use it in GitHub Desktop.
Listening to Firestore changes in Flutter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Importing firestore package | |
| import 'package:cloud_firestore/cloud_firestore.dart'; | |
| import 'package:flutter/material.dart'; | |
| class TODOList extends StatelessWidget { | |
| // Setting reference to 'tasks' collection | |
| final collection = Firestore.instance.collection('tasks'); | |
| @override | |
| Widget build(BuildContext context) { | |
| return Scaffold( | |
| appBar: AppBar( | |
| title: Text('TODO app'), | |
| ), | |
| // Making a StreamBuilder to listen to changes in real time | |
| body: StreamBuilder<QuerySnapshot>( | |
| stream: collection.snapshots(), | |
| builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { | |
| // Handling errors from firebase | |
| if (snapshot.hasError) | |
| return Text('Error: ${snapshot.error}'); | |
| switch (snapshot.connectionState) { | |
| // Display if still loading data | |
| case ConnectionState.waiting: return Text('Loading...'); | |
| default: | |
| return ListView( | |
| // Got rid of Task class | |
| children: snapshot.data.documents.map((DocumentSnapshot document) { | |
| return CheckboxListTile( | |
| title: Text(document['name']), | |
| value: document['completed'], | |
| // Updating the database on task completion | |
| onChanged: (newValue) => collection.document(document.documentID).updateData({'completed': newValue}) | |
| ); | |
| }).toList(), | |
| ); | |
| } | |
| }, | |
| ), | |
| floatingActionButton: FloatingActionButton( | |
| onPressed: () => Navigator.pushNamed(context, '/create'), | |
| child: Icon(Icons.add) | |
| ), | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment