I'm using StreamBuilder to load data from the Firebase Firestore database and keep track of it, and it works fine.
The problem is that I keep receiving updates even when the page is not visible to the user, which could be bad for performance, data usage, and Firebase read cost.
I'm using MaterialPageRoute to navigate between pages.
So to transition from the page containing the StreamBuilder (page A) to the new page (page B). I'm using this method:
Navigator.restorablePushNamed(context, "page-b");
Page A code:
class PageA extends StatelessWidget {
const PageA ({super.key, required this.controller});
static const routeName = '/page-a';
final PageAController controller;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Page A'),
),
body: StreamBuilder<String>(
stream: controller.getLiveDataAsStream(),
builder: (context, snapshot) {
log("New Data Received!");
// Build the UI based on the received data
}
},
),
);
}
When the user is on page B and new data is received, I can still see the log: 'New Data Received!'
So my question is: Is there any easy way I can stop receiving data from the Stream after leaving Page A until it is visible again?