首页 > 解决方案 > 在 Xamarin.Forms Shell 应用程序中首次启动时出现导航错误

问题描述

我的应用程序的主页正在检查用户信息。根据某些条件,弹出窗口显示导航到带有 web 视图的页面。我使用标准方法导航到它:

await Shell.Current.Navigation.PushAsync(new BindCardPage(user.uid), false);

但是,当我第一次启动应用程序时,在尝试导航到 webview 页面后会抛出 NRE:

System.NullReferenceException: Object reference not set to an instance of an object.
 at Xamarin.Forms.ShellSection.OnPushAsync (Xamarin.Forms.Page page, System.Boolean animated) [0x00013] in D:\a\1\s\Xamarin.Forms.Core\Shell\ShellSection.cs:514 
 at Xamarin.Forms.ShellSection+NavigationImpl.OnPushAsync (Xamarin.Forms.Page page, System.Boolean animated) [0x00000] in D:\a\1\s\Xamarin.Forms.Core\Shell\ShellSection.cs:714 
 at Xamarin.Forms.Internals.NavigationProxy.PushAsync (Xamarin.Forms.Page root, System.Boolean animated) [0x00013] in D:\a\1\s\Xamarin.Forms.Core\NavigationProxy.cs:117 
 at Xamarin.Forms.Shell+NavigationImpl.OnPushAsync (Xamarin.Forms.Page page, System.Boolean animated) [0x00000] in D:\a\1\s\Xamarin.Forms.Core\Shell\Shell.cs:1161 
 at Xamarin.Forms.Internals.NavigationProxy.PushAsync (Xamarin.Forms.Page root, System.Boolean animated) [0x00013] in D:\a\1\s\Xamarin.Forms.Core\NavigationProxy.cs:117 

但是当我再次启动一个应用程序(条件没有改变)时,相同的弹出窗口导航到一个没有问题的页面。我尝试添加一个空的构造函数并设置一个默认值,但它没有帮助。查看断点 - 我传递的所有数据都不为空,WebView 组件也不为空。这是一个奇怪的错误,我不知道如何处理它

我的 Xamarin.Forms 版本是4.4.0.991537

标签: xamarinxamarin.formsxamarin.shell

解决方案


发生了类似的崩溃,现在问题似乎是 shell 正在将一个空页面推送到 4.2.xxx 及更高版本的 NavStack 中,这很烦人,但就是这样。OnBackButtonPressed我能够通过在我的 Apps Shell 类中编写以下代码来解决这个问题。

    protected override bool OnBackButtonPressed()
    {
        if (Application.Current.MainPage.GetType() == typeof(AppShell) && Shell.Current.Navigation.NavigationStack.Where(x => x != null).Any())
        {
            return base.OnBackButtonPressed();
        }
        else
        {
            System.Diagnostics.Process.GetCurrentProcess().CloseMainWindow();
            return true;
        }
    } 

AppShell 是我的自定义 Shell 类。

如果您有任何问题,Goodluck 随时回复


推荐阅读