D31
D31

Reputation: 112

How to get realtime updates from firestore and yet keep build method pure?

From this answer:

The build method is designed in such a way that it should be pure/without side effects.

and

This means that the build method should not trigger an http call or modify any state.

But this contradicts with firestore plugin usage example(condensed for briefness):

class BookList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('books').snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
      //  do something with books
      },
    );
  }
}

Anytime when build method called, builder function from StreamBuilder called as well.

What I tried:

...
stream: Firestore.instance.collection('books').snapshots().distinct(),
...

Neither advice from previously mentioned answer works for this case.

Upvotes: 0

Views: 131

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277037

The solution is the same actually: Make a StatefulWidget

class Foo extends StatefulWidget {
  @override
  _FooState createState() => _FooState();
}

class _FooState extends State<Foo> {
  Stream<QuerySnapshot> stream;

  @override
  void initState() {
    super.initState();
    stream = Firestore.instance.collection('books').snapshots();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: stream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        //  do something with books
      },
    );
  }
}

Upvotes: 2

Related Questions