Pre-Load pages on xamarin forms

Viewed 605

I was searching for tricks to make my Xamarin Forms app faster, and I came across this article. Well, I have tried out some options there but I am finding it difficult to achieve the last option that says;

  • Pre-Load screens: This improved by a lot the performance on the app itself what we did is load on each screen, on background, the views and view-models that where needed next, so when pushing them onto the navigation stack they were already loaded. This reduced by a lot the time on transition between pages.

This seems to me as a good option and what I have done is to insert pages I maybe needing next onto the Stack before navigating to the page like so; however, I don't know if I am doing this the right way.

    public ProductHomePageViewModel()
    {
        Application.Current.MainPage.Navigation.InsertPageBefore(new TilePage(), Application.Current.MainPage.Navigation.NavigationStack[0]);
    }

But this doesn't work well when it is done on a homepage where a click of a back button should exit the app. But in this case clicking the back button navigates to the next page on the stack.

Please assist me on how to pre-load pages. Any advice is good. Thank you!

1 Answers

Like I said in the comments, you could use some kind of Singleton Pattern, but for pages.

I'll pust an example. Consider the following code

public partial class Page1 : ContentPage
    {
        private static Page1 _myinstance;
        public static Page1 myinstance
        {
            get
            {
                Prepare();
                return _myinstance;
            }
        }

    public static void Prepare()
    {
        if (_myinstance == null)
        {
            _myinstance = new Page1();
        }
    }

    public Page1()
    {
        InitializeComponent();
    }
}

For any other Page, you could call Navigation.PushAsync(Page1.Instance) . If Page1 was instanced, it will not run the constructor again, just the first time Instance is called.

But if you want to "Prepare" it beforehand, you could call in a background method the Page1.Prepare()

Remember, the constructor will be executed only once. So the page will be like "Cached"

Related