7

Seems like a simple question, but I haven't been able to find a simple answer. Essentially I want to choose which page in the app to start on based on some stored state. I added a GoToAsync call in the AppShell constructor, but this didn't work--which makes sense because the AppShell hasn't been fully constructed yet.

I found this answer, but it feels like it kind of skirts around the issue:

Maui AppShell - Navigate on Open

Where is the best place to inject some code that will run once on startup and can successfully navigate a .NET Maui app to a chosen page?

Ryan
  • 123
  • 1
  • 9

1 Answers1

4

After playing around with overrides, it seems like overriding Application.OnStart works! Shell.Current is set at this point and navigation works.

Here's additional code that allows for asynchronous initialization and uses a Loading Page until the initialization is complete:

using MyApp.Services;
using MyApp.UI;

namespace MyApp;

public partial class App : Application
{
    ConfigurationProviderService m_configProvider;

    public App(ConfigurationProviderService configProvider)
    {
        m_configProvider = configProvider;

        InitializeComponent();

        MainPage = new LoadingPage();
    }

    protected override void OnStart()
    {
        var task = InitAsync();

        task.ContinueWith((task) =>
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                MainPage = new AppShell();

                // Choose navigation depending on init
                Shell.Current.GoToAsync(...);
            });
        });

        base.OnStart();
    }

    private async Task InitAsync()
    {
        await m_configProvider.InitAsync();
    }
}
Ryan
  • 123
  • 1
  • 9
  • 1
    I tried your aproach, and I always got the following exception: System.Exception: 'Relative routing to shell elements is currently not supported. Try prefixing your uri with ///: ///main' – Wasyster Feb 07 '23 at 19:41
  • @Wasyster try "///main" or "///" + nameof(main) whatever way you're doing it. – MathCrackExchange Apr 16 '23 at 19:51
  • @Wasyster I also found tha tre-ordering the "" entries in AppShell.xaml effectively sets the first page to LoginPage if that's what's first listed. This means you don't need any of the above code to start out statically on a certain page. You then, once the user hits login, switch the page to your normal "///" + nameof(MainPage). Also note that if you were experience things breaking with switching some other way, this should fix that. Because it's the most natural. Now my dark/light works – MathCrackExchange Apr 16 '23 at 20:03