Skip to content Skip to sidebar Skip to footer

Memory Used By Pushing A Lot Of Pages On Xamarin.forms' Navigationpage

I have a Xamarin.Forms NavigationPage and I noticed that after pushing quite a lot of pages (say 20), the app starts being laggy and might freeze at some point. I'm guessing it mus

Solution 1:

For solutions with multiple pages and large navigation stack You could use PagesFactory:

public static class PagesFactory
{
    static readonly Dictionary<Type, Page> pages = new Dictionary<Type, Page>();

    static NavigationPage navigation;
    public static NavigationPage GetNavigation()
    {
        if (navigation == null)
        {
            navigation = new NavigationPage(PagesFactory.GetPage<Views.MainMenuView>());
        }
        return navigation;
    }

    public static T GetPage<T>(bool cachePages = true) where T : Page
    {
        Type pageType = typeof(T);

        if (cachePages)
        {
            if (!pages.ContainsKey(pageType))
            {
                Page page = (Page)Activator.CreateInstance(pageType);
                pages.Add(pageType, page);
            }

            return pages[pageType] as T;
        }
        else
        {
            return Activator.CreateInstance(pageType) as T;
        }
    }

    public static async Task PushAsync<T>() where T : Page
    {
        await GetNavigation().PushAsync(GetPage<T>());
    }

    public static async Task PopAsync()
    {
        await GetNavigation().PopAsync();
    }

    public static async Task PopToRootAsync()
    {
        await GetNavigation().PopToRootAsync();
    }

    public static async Task PopThenPushAsync<T>() where T : Page
    {
        await GetNavigation().PopAsync();
        await GetNavigation().PushAsync(GetPage<T>());
    }
}

Post a Comment for "Memory Used By Pushing A Lot Of Pages On Xamarin.forms' Navigationpage"