Flutter: navegue a una nueva pantalla y borre todas las pantallas anteriores

2 minutos de lectura

solía Navigator.push hasta 6 pantallas para llegar a la página de pago. Después del pago, quiero ir a la página “Pago exitoso” y luego eliminar todas las pantallas anteriores, es decir, usar el botón Atrás volverá a la primera pantalla.

NOTA: he probado pushReplacementNamed y no funciona

  • Probé pushReplacementNamed y no funciona. Probablemente hiciste algo mal.

    – Günter Zöchbauer

    7 oct 2018 a las 13:41

  • No, no lo hice. usando pushRepalcementNamed me lleva a una nueva ruta, pero cuando uso el botón Atrás me lleva a la última ruta nombrada en lugar de que el botón Atrás no funcione.

    – Kingsley California

    7 oct 2018 a las 13:47

  • Tal vez desee eliminar más rutas anteriores como docs.flutter.io/flutter/widgets/Navigator/… pero su pregunta no contiene ninguna información que permita diagnosticar su problema.

    – Günter Zöchbauer

    7 oct 2018 a las 13:50

  • Sí. Me acabo de enterar ahora. Aunque gracias

    – Kingsley California

    7 oct 2018 a las 13:54

Me lo imaginé. Era el Navigator.pushAndRemoveUntil función. Donde tuve que pasar el PaymentSuccessful widget como el newRoutey el "/Home" ruta como el predicado

  _navPaymentSuccessful(){
    Navigator.pushAndRemoveUntil(
      context, 
      MaterialPageRoute(
        builder: (context) => PaymentSuccessful()
      ), 
     ModalRoute.withName("/Home")
    );
  }

  • ¿Puede explicar cuál es el propósito de usar ModalRoute.withName('/Home') para completar tu respuesta?

    – iDecodificar

    6 de enero de 2021 a las 15:55

  • @iDecode Puede consultar la documentación aquí [api.flutter.dev/flutter/widgets/Navigator/… the ModalRoute.withName(‘/Home’) is used to ensure that when the back button is pressed the user is navigated to the “/Home Screen” -> “To remove routes until a route with a certain name, use the RoutePredicate returned from ModalRoute.withName”

    – Chichebe

    Nov 22, 2021 at 8:46

  • If you want to navigate to the root Screen, the replace "/Home" with "/". And you can also provide route arguments to MaterialPageRoute() using his props settings: RouteSettings(arguments: myArgs)

    – Manu

    Nov 30, 2021 at 13:02

  • to add more, here is the video explaining exactly this function: Tutorial Link

    – Hardik

    Jan 19, 2022 at 12:58


Accepted Answer is correct. But you can try this too.

Navigator.pushAndRemoveUntil<dynamic>(
        context,
        MaterialPageRoute<dynamic>(
          builder: (BuildContext context) => YourPageNameGoesHere(),
        ),
        (route) => false,//if you want to disable back feature set to false
);

even simpler and I think a better way would be to do it this way,
this Schedules a callback for the end of the current persistent frame,to push to route /loginPage and removes all the previous routes,this way you can make sure that all the frames are rendered and then you navigate to next page.

 SchedulerBinding.instance.addPostFrameCallback((_) {
                Navigator.of(context).pushNamedAndRemoveUntil(
                    '/loginPage', (Route<dynamic> route) => false);
              });

dartKnightRises's user avatar
dartKnightRises

I would Suggest use WillPopScope in your Payment successful page and onWillPop method write following snippet of code:

 return WillPopScope(
      onWillPop: (){
        Navigator.of(context)
            .pushNamedAndRemoveUntil('/Home', (Route<dynamic> route) => false);
      },
      child: Scaffold()
};

¿Ha sido útil esta solución?