Home > Blockchain >  How to pop 2 screen at once in flutter
How to pop 2 screen at once in flutter

Time:10-06

I have not created any routes to navigate between screens. I use Navigator to navigate:

Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage()));

what I have done is navigate to four screens from homePage to success screen:

HomePage => CreatePostScreen => CreateImagePost => SuccessfulScreen

when I reach to successfulscreen I would like to pop two screens and get back to CreatePostScreen. I do not want to write Navigator.pop(context) two times.

I tried to use this, but it will come up with a black screen:

Navigator.popUntil(context, (route) => route is CreatePostScreen);

but this is not working. I would like to learn how flutter handles widget navigation not by route names and solution to this.

I know something about how navigator class handles with route name but I would like to know how to solve it if I push widgets and its working.

CodePudding user response:

What you're trying to do :

Navigator.popUntil(context, (route) => route is CreatePostScreen);

Doesn't work because route is of type Route, not a widget. This leads to all the routes being popped since no Route satisfies your predicate.

What you should do is push your route with a setting, e.g. :

Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage(), settings: RouteSettings(name: "/home")));

And then use that in your predicate. E.g. :

Navigator.popUntil(context, (route) => route.settings.name == "/home");

CodePudding user response:

You would try with the below code: onPressed: () async {int count = 0; Navigator.of(context).popUtil((_)=> count >= 2);}

The code you would refer from is that, you would implement the logic to let the system indicate that whether pop continue, if it return false it will keep pop until it the logic return true void popUntil(bool Function(Route<dynamic>) predicate)

CodePudding user response:

Hope this will help you. You can use popUntil method of Navigation Class.

int count = 0;
Navigator.of(context).popUntil((_) => count   >= 2);
  • Related