Native跳转Flutter页面传参

2,216 阅读1分钟

Native跳转Flutter页面传参,例如一些用户信息(token,uid等)

方式一:通过路由

Android 端代码


    protected void onCreate(Bundle savedInstanceState) {

        //强烈建议放到Application里初始化,初始化一次即可,放这里只是举个例子
        FlutterMain.startInitialization(this);
       
       //Map转为JsonString 下面根据自己实际情况修改
        Map<String,Object> map = getHeaderInfo();
        Gson gson = new Gson();
        String mockUser = gson.toJson(map);
        
        //intent的参数设置必须在super.onCreate之前,因为super.onCreate里会取这些参数
        Intent intent = getIntent();
        intent.setAction("XXXX");
        intent.putExtra("route", mockUser);
        super.onCreate(savedInstanceState);
        FlutterView flutterView =  getFlutterView();
        flutterView.enableTransparentBackground();
        initMethodChannel();
        
    }

iOS 端代码

待补

Flutter

Widget _buildWidget() {

    String initParams = window.defaultRouteName;
    Map<String,dynamic>header = json.decode(initParams);
    //拿到数据了 做你的逻辑
    TODO
    …… ……
    TODO End
    return HomePage();
  }
  
 Widget build(BuildContext context) {
     return MaterialApp(
              title: '项目名字',
              debugShowCheckedModeBanner: false,
              home: _buildWidget(),
            ));
}

方式二:通过Channel

  • BasicMessageChannel :用于传递字符串和半结构化的信息
  • MethodChannel :用于传递方法调用(method invocation)
  • EventChannel :用于数据流(event streams)的通信

根据你的业务情况自行选择Channel,以MethodChannel为例:

Android代码

private MethodChannel methodChannel;

protected void onCreate(Bundle savedInstanceState) {

    FlutterMain.startInitialization(this);
    super.onCreate(savedInstanceState);
    FlutterEngine flutterPlugin = new FlutterEngine(this);
    GeneratedPluginRegistrant.registerWith(flutterPlugin);
}
private void initMethodChannel() {
    methodChannel = new MethodChannel(getFlutterView(), GET_USER_INFO);
    methodChannel.setMethodCallHandler(
        (methodCall, result) -> {

            if(methodCall.method.equals("getUser")){

                Map<String,Object> map = getHeaderInfo();
                Gson gson = new Gson();
                String mockUser = gson.toJson(map);
                result.success(mockUser);

            } else {
                result.notImplemented();
                Log.d("tag","调用了失败");
            }
        });
    }

iOS 端代码

待补

Flutter端代码

根据业务选择调用时机
static Future getUser() async {
    String result = await _channel.invokeMethod("getUser");
    Map<String, dynamic> header = json.decode(result);
    *******TODO*******
    // 你的逻辑
  }

另外: 对于代码中的硬编码,可自行去定义