Search code examples
c#xamlxamarin.formsmaui

Why do I get this exception whe calling PopAsync in .NET MAUI?


I'm using Shell. I have this code on a ViewModel that calls the AddReviewPage:

    private async void OnAddReviewClicked()
    {
        var parameters = new Dictionary<string, object>
        {
            { "ProfessionalId", ProfessionalId }
        };

        await Shell.Current.GoToAsync(nameof(AddReviewPage), parameters);
    }

In the AddReviewViewModel after persisting the information on the database I try to go back to the ProfessionalPage:

    private async void OnAddReviewClicked()
    {
        // persistence code 

        if (success == true)
        {
            await App.Current.MainPage.DisplayAlert("Sucess!", "Success!", "OK");

            // This gives me an exception
            await Shell.Current.Navigation.PopAsync();

            // But this code to navigate to the root of the shell works
            // However this isn't the behavior that I want
            //await Shell.Current.GoToAsync("//Main");
        }
    }

I have the Professional and AddReview pages registered on the shell:

<Shell
x:Class="MyApp.Presentation.Mobile.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyApp.Presentation.Mobile"
xmlns:views="clr-namespace:MyApp.Presentation.Mobile.Views"
Shell.FlyoutBehavior="Disabled">

<ShellContent
    Title="LogIn"
    ContentTemplate="{DataTemplate views:LogInPage}"
    Route="LogInPage" />

<TabBar Route="Main">
    <!-- My main tabs -->
</TabBar>

<ShellContent
    Title="Professional"
    ContentTemplate="{DataTemplate views:ProfessionalPage}"
    Route="ProfessionalPage" />
<ShellContent
    Title="AddReview"
    ContentTemplate="{DataTemplate views:AddReviewPage}"
    Route="AddReviewPage" />

They are also registered on the code behind:

public partial class AppShell : Shell
{
public AppShell()
{
    InitializeComponent();

    Routing.RegisterRoute(nameof(LogInPage), typeof(LogInPage));
    Routing.RegisterRoute(nameof(ProfessionalPage), typeof(ProfessionalPage));
    Routing.RegisterRoute(nameof(AddReviewPage), typeof(AddReviewPage));
}
}

However when I run the OnAddReviewClicked code I get this exception. enter image description here

But the navigation stack is not empty. Am I doing the routes wrong? enter image description here


Solution

  • There is an similar issue about GotoAsync build in back button does not go back to previous page, when working with 3 or more pages. And the is bug still in the maui.

    The cause for this problem is you register the page both in the xaml and the AppShell.cs. So you can check the route you registered in the AppShell.cs and the AppShell.xaml and make every page just be registered once.

    In addition, you can also register the route of Main in AppShell.xaml, and all other routes in AppShell.xaml.cs