How can i pass arguments from my native code to flutter via intent?

Viewed 428

i am launching a specific route in flutter using Intent like below

class NotificationService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        if(remoteMessage.data.isNotEmpty()) {
            val intent = Intent(this, MainActivity::class.java)
            intent.putExtra("route","/specific_route_name");
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent);
        }
    }
}

and my onGenerated function is responsible to handle and launch that flutter screen like below

static Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case '/':
        return CupertinoPageRoute(builder: (_) => MyHomePage());
      case '/specific_route_name':
        return CupertinoPageRoute(builder: (_) => SpecificPage());
      default:
        return CupertinoPageRoute(
          builder: (_) => Scaffold(
            body: Center(
              child: Text('No route defined for ${settings.name}'),
            ),
          ),
        );
    }
  }

now how can i pass data too? via that intent i tried intent.putExtra("data") & intent.putExtra("argument") (just tried my dumb luck)

1 Answers

Well.. you don't (need to). Simply encode everything into the root path.. like /specific_route_name?foo=bar and then use something like:

    final uri = Uri.parse(settings.name);
    final route = uri.path;
    final param = uri.queryParameters['foo'];

this way you will have your route name in route and can read out your parameters through uri.queryParameters.

Related