Created
April 16, 2018 04:34
-
-
Save branflake2267/0a280f880a765e4847b11aa69dab9bc4 to your computer and use it in GitHub Desktop.
Flutter - Cloud Firestore Streaming to a List
This file contains 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
import 'package:cloud_firestore/cloud_firestore.dart'; | |
import 'package:flutter/material.dart'; | |
void main() => runApp(new MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return new MaterialApp( | |
title: 'Flutter Demo', | |
theme: new ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: new MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
@override | |
_MyHomePageState createState() => new _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
@override | |
void initState() { | |
// Firestore.instance.collection('mountains').document() | |
// .setData({ 'title': 'Mount Baker', 'type': 'volcano' }); | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return new Scaffold( | |
appBar: new AppBar( | |
title: new Text("Home"), | |
), | |
body: new MountainList(), | |
floatingActionButton: new FloatingActionButton( | |
child: new Icon(Icons.add), | |
onPressed: () { | |
Firestore.instance.collection('mountains').document().setData( | |
{ | |
'title': 'Mount Vesuvius', | |
'type': 'volcano', | |
}, | |
); | |
}, | |
), | |
); | |
} | |
} | |
class MountainList extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return new StreamBuilder( | |
stream: Firestore.instance.collection('mountains').snapshots, | |
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { | |
if (!snapshot.hasData) return new Text('Loading...'); | |
return new ListView( | |
children: snapshot.data.documents.map((document) { | |
return new ListTile( | |
title: new Text(document['title']), | |
subtitle: new Text(document['type']), | |
); | |
}).toList(), | |
); | |
}, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://youtu.be/Ak_6_pBBe3U - Youtube that covers this source.