MAUI: NullReferenceException when DisplayAlert in Android Emulator

582 Views Asked by At

I have a .NET MAUI project and just want to display an alert. This already worked well, but in some cases it throws me a NullRefereceException. The Code is:

private async void Info_Appearing(object sender, EventArgs e)
{
    await Application.Current.MainPage.DisplayAlert("Title", "Text", "OK");
}

I totally have no clue, what the problem is. The stack trace is: enter image description here

It seems it's a problem of the Android debugger/emulator, because with my local Android device, everything works fine...

Thank you for helping :)

1

There are 1 best solutions below

4
On

Make sure that you have set the MainPage in constructor before it is assigned to the MainPage property of your App. Otherwise, when using the App.Current.MainPage before then, it might throw a NullReferenceException.

As an alternative workaround, you can refer to the snippets below:

      public static Page rootPage { get; set; } 
      public App()
      {
            InitializeComponent();

            MainPage = new MainPage();
            App.rootPage = MainPage;
      }

private async void Button_Clicked(object sender, EventArgs e) 
{
     await App.rootPage.DisplayAlert("Title", "Text", "OK");
}