Login Design Pattern

Xamarin start off by recommending that you show any login page via a PushModalAsync on the navigation stack.

I never liked that because it would keep login and registration sequences in your main app navigation, even though I know you can’t go back to it. But it could also so a flicker when it goes to your main page, then jumps to your login screen if you aren’t logged in.

I did discover a way to avoid this and then also found others had come up with this same method.

Create multiple navigation pages. One with your login page(s) and the other with your main app pages.

In your App.cs (or App.xaml.cs)

public static void SwitchNavigationStack(StackEnum stack)
{
    switch (stack)
    {
        case StackEnum.Login:
            Current.MainPage = GetLoginStack();
            break;
        case StackEnum.Main:
        default:
            Current.MainPage = GetMainStack();
            break;
    }
}

// Just as an example
private static Page GetMainStack()
{
    return new NavigationPage(new MainPage());
}

private static Page GetLoginStack()
{
    return new NavigationPage(new LoginStack());
}

Change the main navigation page as you see fit. Then no back buttons ever cross over onto a navigation flow they shouldn’t be on.

Personally I use this pattern to also break out navigation flows within an app if they get too complex. This pattern is made easier with my Exrin MVVM Framework, as it is built in, using what I call stacks.


XAMARIN WEEKLY NEWSLETTER

Subscribe to a hand-picked round up of the best Xamarin development links every week. Published every Friday. Free.

Signup to Weekly Xamarin

* I do not maintain or run this newsletter, but I do recommend it.

Related Posts

Microsoft MVP | Xamarin MVP | Xamarin Forms Developer | Build Flutter

2 Comments

  1. Sasha K.

    MainPage is not a static property, so to use it from a static method I believe you have to use Current.MainPage = ….

    Current is a static property.

    I’m new to Xamarin Forms so I’m not sure if this used to be different and it was changed or what the case is.

    1. Adam Pedley

      You are right in that MainPage isn’t static, and that would have been fine, if I didn’t make the methods static. I’ll correct the code, thanks for letting me know.