Share via

No Internet page problems

Eduardo Gomez Romero 1,375 Reputation points
2024-11-29T22:01:58.0466667+00:00

I have an interface

    public interface IConnectivityService
    {
        Task InitializeAsync();
    }

and a implementation

 class ConnectivityService(IConnectivity connectivity, IAppService appService): IConnectivityService
 {
     public async Task InitializeAsync()
     {
         connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
         await CheckInitialConnectivity();
     }
     private async Task CheckInitialConnectivity()
     {
         if (connectivity.NetworkAccess != NetworkAccess.Internet)
         {
             await NavigateToNoInternetPage();
         }
     }
     private async Task NavigateToNoInternetPage()
     {
         await MainThread.InvokeOnMainThreadAsync(async () =>
         {
             await appService.NavigateToPage(nameof(NoInternetPage));
         });
     }
     private void Connectivity_ConnectivityChanged(object? sender, ConnectivityChangedEventArgs e)
     {
         if (e.NetworkAccess != NetworkAccess.Internet)
         {
             MainThread.BeginInvokeOnMainThread(async () =>
             {
                 await appService.NavigateToPage($"{nameof(NoInternetPage)}");
             });
         }
         else
         {
             MainThread.BeginInvokeOnMainThread(async () =>
             {
                 await appService.NavigateBack();
             });
         }
     }

since the shell is the first page that loads, I figure that I can use it here

  public AppShell(AppShellViewModel appShellViewModel, IConnectivityService connectivityService)
  {
      InitializeComponent();
      BindingContext = appShellViewModel;

      Routing.RegisterRoute(nameof(TurbineDetailPage), typeof(TurbineDetailPage));
      Routing.RegisterRoute(nameof(ArticleDetailsPage), typeof(ArticleDetailsPage));
      Routing.RegisterRoute(nameof(NoInternetPage), typeof(NoInternetPage));

      RenderBasedOnDevice(DeviceInfo.Idiom);

      connectivityService.InitializeAsync().ConfigureAwait(false);
  }

the problem

If I turn of the internet, it will throw an error

System.NullReferenceException: 'Object reference not set to an instance of an object.' Microsoft.Maui.Controls.Shell.Current.get returned null.

but if I have internet it would navigate normally

Developer technologies | .NET | .NET Multi-platform App UI

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.