Home > front end >  Flutter: StreamBuilder gets other firestore documents when updating a single document
Flutter: StreamBuilder gets other firestore documents when updating a single document

Time:08-25

I have a Stream like this:

@override
  void initState() {
    super.initState();
    rentsStream = FirebaseProfile().getRents(widget.portfolio.id);
  }

Widget _rentsStream() {
    return StreamBuilder<QuerySnapshot>(
      stream: rentsStream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) return Text('Error: ${snapshot.error}');
        if (!snapshot.hasData) return const Loader();
        if (snapshot.data == null) return const Loader();

        rents = snapshot.data!.docs;
        return _portfolioBuilder(context);
      },
    );
  }

The stream is declared outside in order to not rebuild the stream every time I change the state.

Here I get a list of rents. When I modify one of them, this one gets updated but the problem is that it comes with the rest of rents incrementing the documents reads monthly quota (and also I don't need to get again the non updated ones).

Also it triggers with some state changes inside the page I return from the StreamBuilder. Video: https://youtu.be/RPid3Jn_UYQ Each rent card has this:

onTap: () {
          Provider.of<MyRents>(context, listen: false)
              .updateCurrentRentIndex(widget.index);
          Navigator.of(context).pushNamed(
            '/rent',
            arguments: {
              'newRent': widget.rent,
              'portfolioId': widget.portfolioId
            },
          ).then((value) => calculateProfitsExpenses());
      }

Is possible to just get the one I updated? Otherwise I'd need to save them locally and update the rents based on what I changed.

CodePudding user response:

What platform are you running this on? On native mobile, the Firestore caches documents by default and (while your code will get called with all documents) only the modified ones are actually read from the server. Let me repeat that: while your snapshot listener gets called with all documents in the query, many of those may be coming from the local cache and those won't cause charged reads on the server.

This local persistence caching is also available on Web, but there you have to explicitly enable it.

  • Related