Flutter: How to pop/navigate to diferent routes depending on where you came from

104

You can pass an atribute in your class that can be reached from various part of the app.

class YourClass extends StatefulWidget {
  final String whereICameFrom;
  
  YourClass({@required this.whereICameFrom});
  
  @override
  YourClassState createState() => YourClassState();
}

and in your WillPopScope you can use this atribute in a switch case, for example:

onWillPop: () async {
     switch(widget.whereICameFrom){
        case "StatefulWidget1":
          Navigator.of(context).popUntil((route) => route.isFirst);
          break;
        case "StatefulWidget2":
          Navigator.of(context).pop();
          break;
     }
    return false;
  },
Share:
104
Niera
Author by

Niera

Updated on November 27, 2022

Comments

  • Niera
    Niera over 1 year

    I have a widget that I can come from various parts of the app. How can I do so that if I come from a StatefulWidget1 push it takes me to the main widget directly and that if I come from a StatefulWidget2 push it makes normal pop between the routes that the stack has.

    My current WillPopScope function is go to main widget always.Below commented I put in pseudocode what I want to do.

    return WillPopScope(
      onWillPop: () async {
          Navigator.of(context).popUntil((route) => route.isFirst);
        //if(the route name of the parent widget where i come via push == analysis)
        //Navigator.of(context).popUntil((route) => route.isFirst);
        // else
        //Navigator.of(context).pop();
        return false;
      },
      child: Scaffold( ...
    

    I've searched about it but can't find anything useful for the problem.

  • Niera
    Niera over 3 years
    I thought there was some way to access the stack and see which is the last item stored. It is a simple solution but it helps me for what I am doing specifically, thank you very much