6

I try to implement a redirection system.

If I receive a notification (from Firebase messaging) when my application is in background, I store the sent route information (e.g: redirect = /medias/details/430) in shared preferences.

When the app opens, I check sharedPrefs (in the main) and if a redirect string is found, I add it to a stream:

MainSingleton().notificationStream.sink.add(redirectTo);

In the initState of my home page, I check if there is a redirect in the stream, and if it's the case, I redirect the user to the corect page with :

  void initState() {
    super.initState();

    MainSingleton().notificationStream.stream.listen((redirect) {
      if (redirect != null) {
        log("Home page found a redirect request: going to $redirect");
        WidgetsBinding.instance!.addPostFrameCallback((_) {
          log("Callback called");
          Application.router.navigateTo(context, redirect);
        });
      }
    });
   }

I got the message "Home page found a redirect request..." when I click the notification, but not the "Callback called", and obviously, not the redirection.

I need to set the app on background again, and resume it a second time to get the redirection.

WidgetsBinding.instance is not null, so I don't know why the callback is not called.

Am I wrong somewhere?

Slot
  • 1,006
  • 2
  • 13
  • 27

1 Answers1

5

I don’t know if it’s a good solution or only a workaround but you can use WidgetsBinding.instance!.ensureVisualUpdate to schedule a new frame, since probably your app is currently not generating any further frame and addPostFrameCallback gets never called.

MainSingleton().notificationStream.stream.listen((redirect) {
  if (redirect != null) {
    log(“Home page found a redirect request: going to $redirect”);
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      log(“Callback called”);
      Application.router.navigateTo(context, redirect);
    });
  }
  WidgetsBinding.instance!.ensureVisualUpdate();
});
Emanuele
  • 131
  • 2
  • 6
  • 2
    Thanks a lot, it works perfectly ! – Slot Jan 26 '22 at 17:33
  • I had the same issue - I couldn't get the addPostFrameCallback to fire. Also tried adding ensureVisualUpdate and it still didn't fire. Not sure why. I ended up using the 'after_layout' package to trigger a call after the first layout had been performed: https://github.com/fluttercommunity/flutter_after_layout See also here: https://stackoverflow.com/questions/49466556/flutter-run-method-on-widget-build-complete – VincentH Mar 20 '23 at 21:47