avioli / uni_links

Flutter plugin for accepting incoming links.
BSD 2-Clause "Simplified" License
563 stars 303 forks source link

Lifecycle of link listener #116

Open JamesMcIntosh opened 3 years ago

JamesMcIntosh commented 3 years ago

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

avioli commented 3 years ago

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?

JamesMcIntosh commented 3 years ago

@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.