0

I have a StreamProvider as follows

Stream<List<Match>> streamMatches() =>
  FirebaseFirestore.instance.collection('matches').snapshots()
    .map((list) => list.docs.map((doc) => Match.fromJson(doc.data(), doc.id)).toList());

StreamProvider<List<Match>>(create: (context) => streamMatches(), initialData: [])

which I use it in a ListView inside a StatelessWidget

   ListView(
      shrinkWrap: true,
      children: _getMatchesWidget(context.watch<List<Match>>())

This is nice because any update to the DB refreshes the stream. However I would like to not have the UI showing the list view change constantly in real-time for new updates (since I believe it might be a bad UX).

I would like to use a pull-on refresh (RefreshIndicator) and update the list view only onRefresh

Of course I also would like to update the list of matches in background when the user is not visualizing the list (e.g. he paused the app).

How can I tell the StreamProvider to update only in certain cases or what other Provider should I use for it?

alexlipa
  • 1,131
  • 2
  • 12
  • 27

1 Answers1

0

You can change this code below:

    context.watch<List<Match>>()

to this:

    context.read<List<Match>>()

.read returns the List<Match> object without listening to it while .watch makes the widget listen to changes on List<Match>

Edit:

When you want to update the List<Match> object, you can call setState which will rebuild the UI and read the latest value of the stream.

You mentioned that you want to refresh the list using the RefreshIndicator.

You can just add the setState to your onRefresh method like below:

    RefreshIndicator(
      onRefresh: () {
       setState(() {
         //This refreshes the list
       });
    
      }
    )
Victor Eronmosele
  • 7,040
  • 2
  • 10
  • 33
  • Ok but that means that for the whole life of the application the list will never change and I don't want that – alexlipa May 28 '21 at 03:38
  • @alexlipa, please check out the latest answer. This should suffice for your use case. – Victor Eronmosele May 28 '21 at 09:09
  • I am using a `StatelessWidget` since I am using `Provider`. I will add it to the question – alexlipa May 28 '21 at 10:22
  • I'll advise updating the widget to a `StatefulWidget`. You don't have to use a `StatelessWidget` just because you're using `provider`. Here's an answer from `provider`'s creator, Rémi Rousselet, explaining this: https://stackoverflow.com/a/59445408/11039164 – Victor Eronmosele May 28 '21 at 10:46