In my Flutter app I have 2 pages: Page1 and Page2. On Page1 I have a button that brings the user to Page2 through this line of code:
Navigator.pushNamed(
context,
'/page2',
arguments: someParam,
),
Page2 uses Scaffold and AppBar through which the user can navigate back to Page1.
In Page2 I get the passed argument with:
ModalRoute.of(context).settings.arguments
Furthermore, Page2 also executes some task that only makes sense if the user really is on Page2.
My observation is that when I am on Page2 and hit that back arrow, it does trigger the build() method of both Page1 and Page2.
Why is that a problem (for me)? The app also received push notifications and when the user opens those, he/she is directed to Page1. However, if the user was on Page2, put the app in background and then opens the notification, through the effect described above it also triggers that background task - which has some hugely negative effect on the user experience.
How can I prevent Page2 form being build() when navigating away from it? Or, if this is not possible or a bad idea, how can I detect in the build() method of Page2 if the current call comes from navigating away?
Thanks and regards!