uni_links icon indicating copy to clipboard operation
uni_links copied to clipboard

Lifecycle of link listener

Open JamesMcIntosh opened this issue 3 years ago • 2 comments

The way that is suggested to handle listening for links is a little bit painful when you have many "page" level widgets in your app and expect that a link could appear when any of them are visible.

Using a WidgetsBindingObserver it is possible to extract the handling of Uris from the lifecycle of the widgets.

@avioli What do you think of this approach?

abstract class LinkObserver with WidgetsBindingObserver {

  LinkObserver.init() {
    WidgetsBinding.instance?.addObserver(this);

    LinkListener.init(handleUri, true);
  }

  void dispose() {
    LinkListener.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      LinkListener.init(handleUri, false);
    }
  }

  void handleUri(Uri uri);

}

main() {
  LinkObserver.init()

  runApp(...)
}

Many thanks James

JamesMcIntosh avatar May 21 '21 02:05 JamesMcIntosh

Can you provide a super simple implementation of this abstract class for two or more "pages", so I can grasp how you see the WidgetsBindingObserver can help? Thanks.

Is the LinkListener this plugin?

avioli avatar May 22 '21 10:05 avioli

@avioli I've mocked up a stripped down version based my "real-world" implementation. There are a couple of comments in there but feel free to ask any clarification.

https://github.com/JamesMcIntosh/uni_links/blob/widgets-binding-observer-example/uni_links/example/lib/main.dart

Using LinkObserver works really well for routing based on Uri but if you need to also do something similar to your current example app then it could probably be done by refactoring LinkListener to be a mixin and mixing it into LinkObserver and MyApp.

JamesMcIntosh avatar May 22 '21 13:05 JamesMcIntosh