Search code examples
flutterdartflutter-web

How can i dynamically replace a widget without opening a new page


hello I want when I click button for example to stay in the same page but view another screen in specific container without duplicating page with different content


Solution

  • You could create an enum with the current selected page.

    enum CurrentPage {
    HomePage,
    LoginPage,
    RegisterPage,
    }
    

    Declare a variable to save the current selected page:

    CurrentPage currentPage = CurrentPage.HomePage;
    

    When you click on a button you change the current page:

    onPressed: (){
    setState(() {
          currentPage = CurrentPage.RegisterPage;
        });
    }
    

    In your code you ask for the current state and accordingly you change the widget:

    Widget content = Container();
    
    switch (currentPage) {
         
         case CurrentPage.HomePage:
            content = HomePage();
           break;
         case CurrentPage.LoginPage:
           content = LoginPage();
           break;
         ....
       }
    

    And this widget is placed in your Widget Tree.