flutterroutesflutter-web

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?


Solution

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