In page A I use StreamBuilder
to render some data,
then I push to B page using Navigator.push
(A’s Stream is not stoped)
I found A’s StreamBuilder builder
is still calling.
/// a complex model with lots of data
class AModel {}
class APage extends StatefulWidget {
const APage({super.key});
@override
State<APage> createState() => _APageState();
}
class _APageState extends State<APage> {
/// Data is pushed via websocket every second
StreamController<List<AModel>> streamController =
StreamController<List<AModel>>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home Page'),
),
body: StreamBuilder(
stream: streamController.stream,
builder: (BuildContext context, snapshot) {
print('This builder not stop after push to B Page');
if (snapshot.data == null) {
return const SizedBox.shrink();
}
final List<AModel> list = snapshot.data!;
return ListView.builder(
itemCount: list.length,
itemBuilder: (BuildContext context, int index) {
return ACell(model: list[index]);
},
);
}),
);
}
}
class ACell extends StatelessWidget {
final AModel model;
const ACell({super.key, required this.model});
@override
Widget build(BuildContext context) {
/// AModel has a complex layout. Here we use a button as an example.
return ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SecondRoute()),
);
},
child: const Text('Push'),
);
}
}
class BRoute extends StatelessWidget {
const BRoute({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('B Page'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('Go back!'),
),
),
);
}
}
Questions:
- After pushing to page B, the data of A is still refreshing. Does this have any impact on performance?
- If so, do I have to turn A’s Stream off manually when pushing to B?
- Flutter doesn’t have a method like
ViewDisappear
, so how can I stop the stream? - Is there any better way?
Thank you very much!
2