How do I detect if app was launched with a route in Flutter web?

I'm currently using named routes to navigate within my app and I'm trying to detect if a route was used to launch the app (Specifically on web).

For example, a user has never opened my app before but they click on a link someone sent them that follows the format myApp.com/content/1234. I need to initialize some libraries and make a network call before that page (or any other page) is shown.

Here's a simplified version of how my app is launched

    MaterialApp(
      title: "My Title",
      onGenerateRoute: router.generateRoute,
      navigatorObservers: [
        FirebaseAnalyticsObserver(analytics: Analytics.analytics),
      ],
      home: Loading(),
      theme: ThemeData( ),
    );

How do I either detect app launch on flutter web or just if the app was launched with a route?

Upvotes: 1

Views: 1125

Answers (2)

Yuriy N.
Yuriy N.

Reputation: 6127

You can use app_links package. It has the method getInitialAppLink(); which always returns the full URL when launched on the web like this:

https://example.com/#/ in case of the root link

or

https://example.com/#/product/123 in case of the deep link.

You can call this method in your main, then parse URL and decide what to do.

void main() async{
   URI? uri = await AppLinks().getInitialAppLink();
  //parse uri
  runApp( MainApp());
}

Upvotes: 0

mfkw1
mfkw1

Reputation: 1161

If you don't want to use Navigator 2 (recommended way of handling navigation when you target web), solution is to use MaterialApp.onGenerateInitialRoutes.

This callback gets called when MaterialApp starts with a given route (in case of Web - URL). In it, you can detect if route requires any additional setup, push some kind of "splash" page which will perform the loading and then redirect to requested route, example implementation below:

MaterialApp(
  // ...
  onGenerateInitialRoutes: (navigator, route) => [
    MaterialPageRoute(
      builder: (context) => SplashScreen(), 
      settings: RouteSettings(
        arguments: SplashScreenArgs(destinationRoute: transformDeeplink(route)),
      ),
    ],
  ),
),

Notice the transformDeeplink function here - you should implement your own logic to decide if entering your app with given route should be allowed. Redirect to other (default) route or display some kind of error page if not.

Upvotes: 2

Related Questions