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

集成Flutter到原生iOS/Android项目时如何向FlutterViewController传递初始化数据

实现方案

你可以通过Flutter引擎初始路由拼接参数的方式实现,属于官方原生支持的轻量方案,无需额外引入第三方依赖,双端实现都很简便:


1. iOS Swift端实现

修改你现有的openProfile方法,在引擎启动后给FlutterViewController设置携带参数的初始路由即可:

@objc
@IBAction func openProfile() {
    print("open profile")
    
    let flutterEngine = FlutterEngine(name: "patient_profile_engine")
    flutterEngine.run()
    
    let profileVC = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
    // 按约定格式拼接参数到初始路由,支持多参数拼接
    profileVC.setInitialRoute("patientProfile?patient_id=123456")
    present(profileVC, animated: true, completion: nil)
}

2. Android Java端实现

初始化Flutter页面时直接传入携带参数的初始路由即可:

public void openProfile() {
    // 拼接参数,格式和iOS端保持一致
    String initialRoute = "patientProfile?patient_id=123456";
    Intent flutterIntent = FlutterActivity
            .withNewEngine()
            .initialRoute(initialRoute)
            .build(this);
    startActivity(flutterIntent);
}

如果你是自行维护FlutterEngine的场景,也可以在引擎初始化完成后调用flutterEngine.getNavigationChannel().setInitialRoute(initialRoute)设置参数。


3. Flutter Dart侧接收参数

在main.dart中直接读取系统默认路由字段,按约定规则解析参数即可:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    // 读取原生传递的完整路由串
    String fullRoute = WidgetsBinding.instance.window.defaultRouteName;
    Map<String, String> params = {};

    // 按约定格式解析参数
    if (fullRoute.contains('?')) {
      List<String> routeParts = fullRoute.split('?');
      List<String> paramPairs = routeParts.last.split('&');
      for (var pair in paramPairs) {
        List<String> kv = pair.split('=');
        if (kv.length == 2) {
          params[kv[0]] = kv[1];
        }
      }
    }

    // 直接使用解析到的参数
    String? patientId = params['patient_id'];

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('患者档案')),
        body: Center(
          child: Text('收到的患者ID:${patientId ?? '未获取到'}'),
        ),
      ),
    );
  }
}

进阶补充

如果需要传递非字符串类型的复杂参数,可以使用官方MethodChannel实现双向通信,在Dart侧初始化完成后主动向原生侧拉取参数即可,实现逻辑也非常简单。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:36:08