Flutter - Firebase Dynamic Link not Working while app is in kill mode

2.4k Views Asked by At

I have integrated Firebase Dynamic link in my Flutter application to open and navigate application users to specific screen in app.

For that first of all I have added below plugin in pubspec.yaml file:

firebase_dynamic_links: ^5.0.5

Then, I have created a separate class to handle related stuffs as below:

  class DynamicLinkService {
  late BuildContext context;

  FirebaseDynamicLinks dynamicLinks = FirebaseDynamicLinks.instance;

  Future<void> initDynamicLinks(BuildContext context) async {
    this.context = context;
    dynamicLinks.onLink.listen((dynamicLinkData) {
      var dynamicLink=dynamicLinkData.link.toString();
      if (dynamicLink.isNotEmpty &&
          dynamicLink.startsWith(ApiConstants.baseUrl) &&
          dynamicLink.contains("?")) {
          //Getting data here and navigating...
          ...
          ...
          ...
      } 
    }).onError((error) {
      print("This is error >>> "+error.message);
    });
  }
}

Now, I am initialising Deep-link as below in my home_screen:

final DynamicLinkService _dynamicLinkService = DynamicLinkService();

and then calling below method in initState()

  @override
  void initState() {
    SchedulerBinding.instance.addPostFrameCallback((_) async {
      await _dynamicLinkService.initDynamicLinks(context);
    });
  }

This is working like a charm! when my application is in recent mode or in background mode.

But the issue is when the application is closed/Killed, clicking on dynamic link just open the app but could not navigate.

What might be the issue? Thanks in advance.

2

There are 2 best solutions below

1
On BEST ANSWER

Let me answer my own question, It might be useful for someone!

So, In above code I forgot to add code to handle dynamic link while the app is in closed/kill mode.

We need to add this code separately:

//this is when the app is in closed/kill mode
final PendingDynamicLinkData? initialLink = await FirebaseDynamicLinks.instance.getInitialLink();
if (initialLink != null) {
  handleDynamicLink(initialLink);
}

So, final code looks like as below:

//this is when the app is in closed/kill mode
final PendingDynamicLinkData? initialLink = await FirebaseDynamicLinks.instance.getInitialLink();
if (initialLink != null) {
  handleDynamicLink(initialLink);
}

//this is when the app is in recent/background mode
dynamicLinks.onLink.listen((dynamicLinkData) {
  handleDynamicLink(dynamicLinkData);
}).onError((error) {
  print("This is error >>> "+error.message);
});

Its working like a charm now! That's All.

1
On

Make sure that your CFBundleURLSchemes in info.plist is set to your app bundle Id as that is the default for firebase dynamic links for some that this answer doesn't solve the problem