Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Push navigator route in build method

Tags:

flutter

dart

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?

like image 263
Alexandre Serra Avatar asked Apr 22 '26 01:04

Alexandre Serra


1 Answers

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');
  }
 });
}
like image 103
Stefano Amorelli Avatar answered Apr 24 '26 18:04

Stefano Amorelli