-
Notifications
You must be signed in to change notification settings - Fork 1.9k
NullReferenceException from ShellToolbar OnBackButtonCanExecuteChanged #11401
Description
Description
In a ContentPage I added a BackButtonBehavior to Call a Command in my ViewModel to call
await Shell.Current.Navigation.PopToRootAsync(false);
The shell pops to root which is nice. But after this I get a NullReferenceException from
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Maui.Controls.ShellToolbar.g__OnBackButtonCanExecuteChanged|11_1(Object sender, EventArgs e)
at CommunityToolkit.Mvvm.Input.AsyncRelayCommand.<set_ExecutionTask>g__MonitorTask|26_0(AsyncRelayCommand this, Task task)
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 Program.Main(String[] args) in //Program.cs:line 14
The root page of the shell does not have a BackButtonBehavior. Only the page I navigated from contains a BackButtonBehavior.
By looking at the code of UpdateBackbuttonBehavior in ShellToolbar I would see the following issue.
If someone calls NotifyCanExecuteChanged after navigating to a page containing no BackButtonBehavior it can happen that _backButtonBehavior is null in OnBackButtonCanExecuteChanged.
Steps to Reproduce
- Create a new Shell App
- Navigate to a Contentpage containing a BackButtonBehavior from root page.
- In Backcommand await Shell.Current.Navigation.PopToRootAsync(false);
- Force Invocation of CanExecute of the Command that Handled the Back Press and still the _backButtonCommand in ShellToolbar
Link to public reproduction project repository
https://github.com/Larhei/Maui-Issues/tree/main/ShellNavigation
Version with bug
6.0.486
Last version that worked well
Unknown/Other
Affected platforms
iOS, Android
Affected platform versions
iOS and android
Did you find any workaround?
Clearing the Command Binding from the BackButtonBehavior during OnNavigatingFrom in my ContetnPage
protected override void OnNavigatingFrom(NavigatingFromEventArgs args)
{
// Remark: Work around for nullpointer during use of BackButtonBehaviour.
var behaviour = Shell.GetBackButtonBehavior(this);
behaviour?.ClearValue(BackButtonBehavior.CommandProperty);
}
causes a OnBackButtonPropertyChanged in ShellToolbar and this unsubscribes the OnBackButtonCanExecuteChanged handler throwing the exception.
Relevant log output
No response