You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java层onNewIntent中调用Flutter pushRoute路由跳转失效如何解决

问题原因

你当前的实现存在两个核心问题:

  • 每次触发onNewIntent时都新建了FlutterEngine实例,这个新实例和你App当前前台运行的Flutter渲染引擎完全无关,你给新引擎发送的路由指令不会作用到当前显示的页面上
  • Java层推送的路由名是process,但Flutter侧注册的路由名是/process,名称不匹配导致路由无法命中
修复方案

方案1:复用现有引擎+修正路由名

直接使用当前Activity绑定的正在运行的Flutter引擎实例,同时修正路由名称即可生效,修改后的Java层代码如下:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if (Intent.ACTION_VIEW.equals(intent.getAction())) {
        Uri uri = intent.getData();
        String paymentId = uri.getQueryParameter("id");
        intent.putExtra("paymentId", paymentId);
        // 复用当前已运行的Flutter引擎,不要新建
        FlutterEngine flutterEngine = getFlutterEngine();
        if (flutterEngine != null) {
            // 路由名加斜杠,和Flutter注册的保持一致
            flutterEngine.getNavigationChannel().pushRoute("/process");
        }
    }
}

方案2:使用MethodChannel通信(更灵活,推荐)

如果需要同时传递paymentId参数到Flutter页,更推荐用自定义MethodChannel实现双向通信,可控性更高:

Java层实现

首先在Activity的onCreate方法中初始化MethodChannel:

// 全局变量
private MethodChannel routeChannel;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 初始化时拿到现有引擎,注册通道
    FlutterEngine engine = getFlutterEngine();
    if (engine != null) {
        routeChannel = new MethodChannel(engine.getDartExecutor().getBinaryMessenger(), "com.yourapp.route_channel");
    }
}

然后在onNewIntent中发送跳转指令:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if (Intent.ACTION_VIEW.equals(intent.getAction()) && routeChannel != null) {
        Uri uri = intent.getData();
        String paymentId = uri.getQueryParameter("id");
        // 调用Flutter侧方法,同时传参
        routeChannel.invokeMethod("navigateToProcess", paymentId);
    }
}

Flutter层实现

在根页面(比如你注册的/路由对应的Init组件)的initState中注册方法监听:

@override
void initState() {
  super.initState();
  const MethodChannel channel = MethodChannel('com.yourapp.route_channel');
  channel.setMethodCallHandler((call) async {
    if (call.method == 'navigateToProcess') {
      // 拿到Java层传递的paymentId,同时可以传递到目标页面
      String paymentId = call.arguments as String;
      Navigator.pushNamed(context, '/process', arguments: paymentId);
    }
  });
}

内容的提问来源于stack exchange,提问作者ontwikkelaar15

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 16:06:03