1

i have a stream which takes data from firebase and when a specific field in firestore changes my app Navigates to next screen (I'm listening to that field in build method) but after reaching to next screen if that value changes again the screen where i was navigated to relaunches itself. How do i stop listening to stream once i am navigated to next stream.

The thing i want to achieve to open a new screen when a value in firestore changes to true. here is my code

 gameProvider.getRoomData().listen((e) {
  Map a = e.data() as Map<String, dynamic>;
  if (a['gameRunning']) {
    Navigator.of(context).push(MaterialPageRoute(
      builder: (context) => GameplayScreen(),
    ));
    
  }
});

getRoomData is the stream i'm listening to and gameRunning is the bool i wanna see if it becomes true i want to navigate to new screen but once i'm there i don't want to listen it's changes

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
  • Check out this page: https://stackoverflow.com/questions/54899927/flutter-streamsubscription-not-stopping-or-pausing – BJW Jan 20 '22 at 19:50

1 Answers1

0

Create a StreamSubscription field and assign it your stream, like:

late StreamSubscription _subscription;

Now, pause the stream before navigating to second screen and resume if after coming back from there:

_subscription = yourStream.listen((e) async {
  if (yourBoolCondition) {
    // Pause the subscription before navigating to another screen.
    _subscription.pause();

    // Navigate to the second screen
    await Navigator.of(context).push(MaterialPageRoute(
      builder: (context) => GameplayScreen(),
    ));

    // Resume the subscription after you have come back to this screen.
    _subscription.resume();
  }
});
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
  • where should i call all of this, currently I'm doing it in build method of my first screen(so that i gey context to access provider) is there a better place to call it, all i want is to open a screen when data in firebase changes – Shuvam Jaswal Jan 20 '22 at 20:06
  • You should call this in your existing code, replace `yourStream` with `gameProvider.getRoomData()` and `yourBoolCondition` with `a['gameRunning']`. – CopsOnRoad Jan 20 '22 at 20:11
  • ur solution worked for me. I have one more question i want to update a variable in provider every time a field changes in firebase, how do i do that? I think i can listen to stream and update the data accordingly in provider class but how do i do that? – Shuvam Jaswal Jan 21 '22 at 11:19