flutter与native交互

Posted suyue

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flutter与native交互相关的知识,希望对你有一定的参考价值。

flutter与native交互

一、dart

  1. 引入包 import \'package:flutter/services.dart\';
  2. 定义通道名并通过 MethodChannel连接
  3. 调用native方法platform.invokeMethod("call_native_method")

`

import \'package:flutter/material.dart\';
import \'package:flutter/widgets.dart\';
import \'dart:async\';
//与原生交互
import \'package:flutter/services.dart\';
class MinePage extends StatefulWidget {
  @override
 _MinePageState createState() => _MinePageState();
}
class _MinePageState extends State<MinePage> {
  static const CHANNEL_NAME = "samples.flutter.study/call_native";
  static const platform = MethodChannel(CHANNEL_NAME);
  String _res = "111";
  @override
 Widget build(BuildContext context) {
    return Column(
      children: [
        RaisedButton(
            onPressed: () async{
              String res = await platform.invokeMethod("call_native_method");
              setState(() {
                _res = res;
              });
            },
            child:Text("调用native")
        ),
        Text(_res),
      ],
    );
  }
}

`

二、native(安卓)

  1. 引用相关flutter包
  2. 继承FlutterActivity类,通过MethodChannel连接相同的通道名称
  3. 写交互的方法

·

package com.example.flutter_app;
import android.content.Context;
import android.os.BatteryManager;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
public class MainActivity extends FlutterActivity {
    String CHANNEL_NAME = "samples.flutter.study/call_native";
    @Override
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new MethodChannel(getFlutterView(),CHANNEL_NAME).setMethodCallHandler(
            new MethodChannel.MethodCallHandler() {
                @Override
 public void onMethodCall(MethodCall methodCall,MethodChannel.Result result){
                  if(methodCall.method.equals("call_native_method")){
                      result.success("native返回值aaa");
                  } else {
                      result.success("I don not know what you said");
                  }
                };
            }
        );
    };
}

·

以上是关于flutter与native交互的主要内容,如果未能解决你的问题,请参考以下文章

Flutter如何与Native(Android)进行交互

Flutter 如何与 Native (Android) 进行交互 | 开发者说·DTalk

Flutter 如何与 Native (Android) 进行交互 | 开发者说·DTalk

cordova与ios native code交互的原理

错误记录Flutter 混合开发获取 BinaryMessenger 报错 ( FlutterActivityAndFragmentDelegate.getFlutterEngine() )(代码片段

如何将消息从 Flutter 传递到 Native?