Search code examples
.netxamlmaui

How to ensure a FlyoutPage's hamburger button is displayed when inital MainPage is not a FlyoutPage?


In my App.xaml.cs's Initialize(), I start the user out on the login page like this:

MainPage = new NavigationPage(new LoginPage());

In the login page, following authentication, I navigate to a FlyoutPage like this:

Navigation.InsertPageBefore(myFlyoutPage, this);
await Navigation.PopAsync();

Later, when I need to send the user back to the login page, I do so as follows:

"Return to login" listing

var page = new LoginPage();
myFlyoutPage.Navigation.InsertPageBefore(page, myFlyoutPage);
await myFlyoutPage.Navigation.PopToRootAsync();

The flyout page uses "Popover" FlyoutLayoutBehavior, so after the login, I expect the rendered FlyoutPage to include a hamburger menu button. However, in my case that button is absent, even though the root page in the stack is a FlyoutPage at that point.

I noticed that if I explicitly set (again) the app's MainPage to myFlyoutPage as part of the post-authentication navigation, then the button is rendered and works as expected.

Navigation.InsertPageBefore(myFlyoutPage, this);
((App)(Application.Current)).MainPage = myFlyoutPage; // added
await Navigation.PopAsync();

However, this causes an exception to be thrown when sending the user back to login (in the "return to login" listing above) on the following line:

myFlyoutPage.Navigation.InsertPageBefore(page, myFlyoutPage);

The exception is as follows:

System.ArgumentException: 'before must be in the pushed stack of the current context'

I can't seem to find any way of displaying the hamburger button without breaking the navigation. Unfortunately, I'm not able to use Shell in this project. Any guidance would be immensely appreciated.


Solution

  • You can add this in your "return to login" listing:

    var page = new LoginPage();
    //myFlyoutPage.Navigation.InsertPageBefore(page, myFlyoutPage);
    await myFlyoutPage.Navigation.PopToRootAsync();
    Application.Current.MainPage = page;
    

    It changes the root page of the application to LoginPage.

    I create a project and test it. This works well.