Alexandre Serra
Alexandre Serra

Reputation: 348

Flutter - Push navigator route in build method

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?

Upvotes: 3

Views: 2169

Answers (1)

Stefano Amorelli
Stefano Amorelli

Reputation: 4854

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');
  }
 });
}

Upvotes: 11

Related Questions