Flutter调用原生方法有3个大步骤:

* 在flutter中调用原生方法
* 在Android中实现被调用的方法
* 在iOS中实现被调用的方法
<>一、在flutter中调用原生方法

在flutter中要调用原生代码需要通过通道传递消息,在flutter端就是MethodChannel。
Future<bool> testAction1() async { // Native channel // 创建一个我们自定义的channel。
const platform = MethodChannel("com.test/testAction1"); bool result = false;
try { // 用channel发送调用消息到原生端,调用方法是:testAction1 result = await
platform.invokeMethod("testAction1"); } on PlatformException catch (e) {
print(e.toString()); } return result; }
<>二、在Android中实现被调用的方法

在flutter项目文件夹里的Android文件夹中有一个
MainActivity.java文件,在MainActivity里注册我们的Android端插件。
public class FlutterNativePlugin implements MethodChannel.MethodCallHandler {
public static String CHANNEL = "com.test/testAction1"; //
注意这里的插件名字要和flutter中的一样 static MethodChannel channel; private Activity activity;
private FlutterNativePlugin(Activity activity) { this.activity = activity; }
public static void registerWith(PluginRegistry.Registrar registrar) { channel =
new MethodChannel(registrar.messenger(), CHANNEL); FlutterNativePlugin instance
= new FlutterNativePlugin(registrar.activity());
channel.setMethodCallHandler(instance); } @Override public void
onMethodCall(MethodCall methodCall, MethodChannel.Result result) { //
onMethodCall这个方法是插件的回调,这里我们根据方法名isChinese判断调用的方法,然后实现我们的操作就行了。 if
(methodCall.method.equals("testAction1")) { boolean test1 = true;
result.success(test1); // 这里直接返回了true,这里只是个例子,而你应该换成你自己的逻辑。 } else {
result.notImplemented(); } } }
MainActivity.java中进行注册
public class MainActivity extends FlutterActivity { @Override protected void
onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this); registerCustomPlugin(this); }
private void registerCustomPlugin(PluginRegistry registrar) {
FlutterNativePlugin.registerWith(registrar.registrarFor(FlutterNativePlugin.CHANNEL));
} }
<>三、在iOS中实现被调用的方法

调用插件代码
import Foundation import Flutter class FlutterNativePlugin: NSObject,
FlutterPlugin { static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "com.test/testAction1",
binaryMessenger: registrar.messenger()) let instance = FlutterNativePlugin()
registrar.addMethodCallDelegate(instance, channel: channel) } func handle(_
call: FlutterMethodCall, result: @escaping FlutterResult) { if call.method ==
"testAction1" { result(true) } else { result(FlutterMethodNotImplemented) } } }
AppDelegate中注册代码
override func application( _ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey:
Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self)
FlutterNativePlugin.register(with: self.registrar(forPlugin:
"FlutterNativePlugin")!) return super.application(application,
didFinishLaunchingWithOptions: launchOptions) }

技术
下载桌面版
GitHub
Gitee
SourceForge
百度网盘(提取码:draw)
云服务器优惠
华为云优惠券
腾讯云优惠券
阿里云优惠券
Vultr优惠券
站点信息
问题反馈
邮箱:[email protected]
吐槽一下
QQ群:766591547
关注微信