2

I am working on flutter application where I am using 3 screens.

MainActivity open to ActivityClass1 and ActivityClass1 will open ActivityClass2. Now when I am taking Navigator.pop(context), from ActivityClass2 it will shows ActivityClass1 from the stack. But this time I need to take initState() of ActivityClass1 as I need to refresh few data on ActivityClass1.

Is there any way to call initState() of ActivityClass1 which also maintain my stack for MainActivity -> ActivityClass1? I have also tried for Navigator.of(context).pushAndRemoveUntil( instead of using Navigator.pop(context), on ActivityClass2 but this will clears my stack.

Kishan sharma
  • 701
  • 1
  • 6
  • 20

3 Answers3

1

Navigator.push returns a Future when the MaterialPageRoute passed into it is resolved. You could await that Future to know when some other view has popped back to it.

Example,

Navigator.of(context).push(MaterialPageRoute(
  builder: 
    (context) => NewView(),
  ),
).then((_) {
  // Call setState() here or handle this appropriately
});

So now when I am coming back to my Activity Class1 this method will help to take any action while comming back to screen by just using Navigator.pop(context),.

Kishan sharma
  • 701
  • 1
  • 6
  • 20
0

If you want to start the initial state of the screen again, you can use pushReplacement instead of Pop() when you want to back. It works for me:

Use pushReplacement to go to ActivityClass2 and to back to ActivityClass1

ActivityClass2 -> ActivityClass1

Navigator.pushReplacement(
  context,
  MaterialPageRoute(
    builder: (context) => ActivityClass1(),
  ),
);
  • I have tried the same solution but this can create a stack like MainActivity() -> Screen1 -> Screen1. So now when I press back from screen1 it will pop again to Screen1. – Kishan sharma Mar 28 '21 at 04:40
0

Instead of using Navigator.of(context).pop, use:

Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => SecondRoute()),
);
Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
  • If I will use the `Navigator.push` call again then this screen will also be added to my stack, so now if I'll press back this will show me like Screen1 -> Screen2 -> Screen1 -> MainActivity. Which is the wrong flow. I need something where it works as screen1 -> MainActivity in my stack after pressing back from screen2. – Kishan sharma Mar 29 '21 at 07:57
  • Use pushReplacement – Tasnuva Tavasum oshin Mar 29 '21 at 09:54