I am trying to navigate inside a streambuilder but I have this error:"setState() or markNeedsBuild() called during build.". If I call navigate inside an onpressed button it works but not by just use it inside a condition. I am stuck. There is some code to show you.
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder(
stream:
Firestore.instance.collection('rooms').document(pinid).snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
if ((snapshot.data['Votes'][0] + snapshot.data['Votes'][1]) >=
snapshot.data['joueurs']) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Results(),
));
}
}
return Center(
child: Text('VOUS AVEZ VOTE'),
);
},
),
);
}
1 Answer. Declare a StreamController with broadcast , then set a friendly name to the Stream of this StreamController , then everytime you want to rebuild the wraped widget (the child of the StreamBuilder just use the sink property of the StreamController to add a new value that will trigger the StreamBuilder .
That's because Flutter is triggering a frame build when you are trying to navigate to another screen, thus, that's not possible.
You can schedule a post frame callback so you can navigate as soon as Flutter is done with tree rebuilding for that widget.
import 'package:flutter/foundation.dart';
WidgetsBinding.instance.addPostFrameCallback(
(_) => Navigator.push(context,
MaterialPageRoute(
builder: (context) => Results(),
),
),
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With