Search code examples
flutterdartnavigationmaterialpageroute

How can I set a condition to navigate to different pages based on the previous page or the current page in flutter


I am working on an app and id like to ask if anyone can help me to understand how using routes I can navigate from my current screen to another page based on the previous page I navigated from. I can navigate to the page through different routes and I want to navigate to separate pages based on my previous routes

I tried using naming the routes in my MainDart and use this bool _isfromreservation = ModalRoute.of(context)!.settings.name == 'reservation'; and add it to the button with an if statement conditioning if this is true.


Solution

  • Hopefully this code help you ..please check this

    enum PaymentScreenComeFrom {
      profileScreen,
      otherScreen,
    }
    
    
    GlobalButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => PaymentScreen(
                      paymentScreenComeFrom: PaymentScreenComeFrom.profileScreen,
                    ),
                  ),
                );
              },
              buttonText: "Profile Screen",
        )
    
    
    
    
    class PaymentScreen extends StatefulWidget {
      const PaymentScreen({
        super.key,
        required this.paymentScreenComeFrom,
      });
    
      final PaymentScreenComeFrom paymentScreenComeFrom;
    
      @override
      State<PaymentScreen> createState() => _PaymentScreenState();
     
    }
    
    class _PaymentScreenState extends State<PaymentScreen> {
      @override
      void initState() {
        super.initState();
        if(widget.paymentScreenComeFrom ==PaymentScreenComeFrom.profileScreen){
          
        }
        
        
      }
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    }