-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Description
Description
When navigating back from a page to the previous page (A) and this page is then navigating forward to another page inside the Shell OnNavigated event, the Handler for the page A will be null. This leads to the next navigation crashing the app under iOS with the following exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Maui.Controls.Platform.Compatibility.ShellSectionRenderer.ElementForViewController(UIViewController viewController)
at Microsoft.Maui.Controls.Platform.Compatibility.ShellSectionRenderer.NavDelegate.WillShowViewController(UINavigationController navigationController, UIViewController viewController, Boolean animated)
--- End of stack trace from previous location ---
at ObjCRuntime.Runtime.ThrowException(IntPtr gchandle)
at UIKit.UIApplication.UIApplicationMain(Int32 argc, String[] argv, IntPtr principalClassName, IntPtr delegateClassName)
at UIKit.UIApplication.Main(String[] args, Type principalClass, Type delegateClass)
at MauiIosNavigationCrashes.Program.Main(String[] args)
This happened after upgrading to .NET 9 with MAUI 9.x.x.
Using .NET 8 and MAUI 8.0.100 this crash does not happen.
There are similar issues already present but they were closed due to inactivity and did not provide a way of reproduction:
- MAUI IOS System.NullReferenceException: Arg_NullReferenceException #30563
- Maui IOS System.NullReferenceException - Arg_NullReferenceException #29294
Steps to Reproduce
- Clone the reproduction repository
- Start the application on iOS
- Click on "Open Page1"
- Click on "OpenModalPage"
- Click on "Close Modal"
- (On Page2) Click on "Navigate to next page"
Actual result:
The app crashes with the exception mentioned above.
Expected result:
The app does not crash.
Link to public reproduction project repository
https://github.com/FinnKr/MauiIosNavigationCrashes
Version with bug
9.0.110 SR11
Is this a regression from previous behavior?
Yes, this used to work in .NET MAUI
Last version that worked well
.NET 8 (MAUI 8.0.100)
Affected platforms
iOS
Affected platform versions
Tested with iOS 18.5 & iOS 26.0
Did you find any workaround?
Edit: The second workaround below is cleaner in my opinion
In our actual use case we could remove the page with a Handler=null from the NavigationStack before navigating. This is only possible because the user is not able to navigate back again after this page.
So under those circumstances a workaround is this:
var pageToRemove = Shell.Current.Navigation.NavigationStack.FirstOrDefault(page => page is { Handler: null });
if (pageToRemove != null)
{
Shell.Current.Navigation.RemovePage(pageToRemove);
}
// Navigate here
Another workaround I found was to move the navigation to the MainThread/Dispatcher:
Application.Current!.Dispatcher.Dispatch(() =>
{
// Navigate here
});
Relevant log output
See exception above