0

I'm running my flutter app on Android emulator with VScode. I want to show a relevant page on app when fcm notification is tapped. My app can receive a notification correctly when app is on background. The app will open up when I tap a notification. However it will show the page last opened and gives errors below:

E/flutter (23056): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
E/flutter (23056): Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.

My code to listen fcm notification action on background is like this:

void initState() {
    fcmListener = FirebaseMessaging.onMessageOpenedApp
        .asBroadcastStream()
        .listen((RemoteMessage message) {
      
      Navigator.of(context).popUntil((route) => route.isFirst); // Errors happen here

      // Open notification details page
      Navigator.push(context, MaterialPageRoute(builder: (context) => ShowPage()));
    });
}

I saw quite few people suggesting "if(mounted){}". It will prevent errors, however that is not an option to me as I still want to open a detals page even when "not mounted". Is there a way to rebuild a lost context like:

if(mounted) {
    // open a page normally
} else {
    // No context, so rebuild it
    rebuildContext();

    // Then open a page
}

Or even make the app keep context?

I put dispose() - still no luck

@override
void dispose() {
    fcmListener.cancel();
    super.dispose();
}

Edit: This app has a login function with Laravel passport and I followed https://medium.com/swlh/authenticating-flutter-application-with-laravel-api-caea30abd57 to built it. I noticed that dispose() is called on login(so context will be lost at this point?). Also, the page will open correctly from notification after restarting project on VScode(so it is rebuilding context at this point?).

ASH
  • 459
  • 5
  • 18

1 Answers1

1

I found a solution. Followed below. Use "navigatorKey.currentContext" for context works fine. https://stackoverflow.com/a/61773774/3213925

ASH
  • 459
  • 5
  • 18