grepLines
grepLines

Reputation: 2558

why widget get built twice when calling Navigator.of(context).pushNamed(..) in flutter?

The build function in the class TestWidget below get called twice when navigation code executed. The Test Widget is printed twice on the console.
Does anyone know why this is the case?

 class TestWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("Test Widget");
    return new Scaffold(body: new Text("TEST WIDGET"),);
  }
}

Navigation code:

   Navigator.of(context).pushNamed(AppRoutes.fieldData);`

Route definition:

  AppRoutes.fieldData: (context) {
           return new TestWidget(); 
  },

Upvotes: 8

Views: 1757

Answers (1)

Fabio Veronese
Fabio Veronese

Reputation: 8360

This happens because of animation.

When a route gets dragged in the page content is built to get a rendered face to be animated in, and then, when it settles into place, it is re-built again.

You can see it clearly placing a debug break in your build function and try to navigate to such route: it will stop first when the route is about to enter - but still not visible -; then when it settles to place.

Upvotes: 5

Related Questions