.NET MAUI在Android模拟器调用DisplayAlert时触发NullReferenceException
.NET MAUI 弹窗提示NullReferenceException 解决办法
问题原因
模拟器/调试器的页面初始化流程比真机慢,当Info_Appearing事件触发时,Application.Current.MainPage可能还未完成赋值,导致空引用异常;真机初始化速度更快,因此不会出现该问题。
解决方法
检查MainPage是否为空后再调用
增加空值判断,避免直接访问null对象:private async void Info_Appearing(object sender, EventArgs e) { if (Application.Current?.MainPage != null) { await Application.Current.MainPage.DisplayAlert("Title", "Text", "OK"); } }改用当前页面的DisplayAlert
直接使用触发事件的当前页面调用弹窗,无需依赖MainPage:private async void Info_Appearing(object sender, EventArgs e) { if (sender is Page currentPage) { await currentPage.DisplayAlert("Title", "Text", "OK"); } }延迟执行适配模拟器
给MainPage初始化留足时间,适合模拟器启动较慢的场景:private async void Info_Appearing(object sender, EventArgs e) { await Task.Delay(100); // 可根据实际情况调整延迟时长 if (Application.Current?.MainPage != null) { await Application.Current.MainPage.DisplayAlert("Title", "Text", "OK"); } }
内容的提问来源于stack exchange,提问作者nicetomitja
相关产品推荐
相关产品推荐

