I have a StreamBuilder object to render a list from a FireStore collection:
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('posts').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
default:
return new ListView(
children:
snapshot.data.documents.map((DocumentSnapshot document) {
return Post(document: document);
}).toList());
}
});
}
I'm trying to make it so that if the snapshot.hasError
, the StreamBuilder tries again. How can i do that?
Generally, you should always combine StreamBuilder
with a stateful widget. Otherwise the stream would be recreated every time the build
method is called.
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Stream<QuerySnapshot> postsStream;
@override
void initState() {
super.initState();
postsStream = Firestore.instance.collection('posts').snapshots();
}
void retryLoad() {
setState(() {
postsStream = Firestore.instance.collection('posts').snapshots();
})
}
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: postsStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return RaisedButton(
child: Text('Retry'),
onPressed: retryLoad,
);
}
// ...
},
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With