Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retry on error with Flutter StreamBuilder?

Tags:

flutter

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?

like image 476
Ozymas Avatar asked Dec 11 '18 09:12

Ozymas


1 Answers

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,
          );
        }
        // ...
      },
    );
  }
}
like image 193
boformer Avatar answered Nov 04 '22 00:11

boformer