Niera
Niera

Reputation: 41

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

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.

Upvotes: 4

Views: 825

Answers (1)

Kennedypz
Kennedypz

Reputation: 472

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;
  },

Upvotes: 1

Related Questions