I'm trying to do something like this in a stateful widget:
@override
Widget build(BuildContext context) {
if (condition) Navigator.pushNamed(context, '/someRoute');
// else, return some widget
return Container(child: someWidget());
}
If condition evaluates to true, flutter is able to push the route. However, an error is thrown: setState() or markNeedsBuild() called during build .
How can I do this without an error?
The build() method of a Widget is used to describe the UI, more specifically:
The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change (e.g., an InheritedWidget referenced by this widget changes). This method can potentially be called in every frame and should not have any side effects beyond building a widget.
Therefore, the build() method is not the right place to call Navigator.pushNamed().
One option would be to do so after the layout has been completely loaded, by overriding the initState() method:
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (true) { // condition here
Navigator.pushNamed(context, '/someRoute');
}
});
}
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