How to use Flutter Firebase dynamic links with go_router

2.1k Views Asked by At

I had firebase dynamic links integrated and working fine in my app and later i changed to use go_router and now i don't know what i should do to get it working or how to handle it.

The way i imagined it would be is that the FB dynamic link path will be the same as the path to the page in GoRouter routes, and go_router will redirect to the page automatically but i don't think that is how it works and i can't find any resources for this.

So the question is how to use Firebase DynamicLinks with go_router?

1

There are 1 best solutions below

0
On

this is how I did it, looks like working fine :)

  • For when the app is in terminated mode:

    Future main() async { ...

    // Closed state: getInitialLink is Used
    final PendingDynamicLinkData? initialLink =
        await FirebaseDynamicLinks.instance.getInitialLink();
    

    ...

then through runApp(MtApp(initialRoute: initialLink)) pass it to GoRouter.initialLocation field or GoRouter.redirect function, depending on how you use it.

  • For when the app is in background:

wrap your top widget with a statefulWidget your created like:

class AHDynamicLinksManager extends

 StatefulWidget {
  final Widget child;
  const AHDynamicLinksManager({required this.child, Key? key})
      : super(key: key);

  @override
  State<AHDynamicLinksManager> createState() => _AHDynamicLinksManagerState();
}



class _AHDynamicLinksManagerState extends State<AHDynamicLinksManager> {

  @override
  void initState() {
    super.initState();
    FirebaseDynamicLinks.instance.onLink.listen((dynamicLinkData) {
      String goingTo = dynamicLinkData.link.path;
      GoRouter.of(context).go(goingTo);
    }).onError((error) {
      GoRouter.of(context).go("/errorpage/$error");
    });
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

Hope it helped!