目录:
- 关于 Flutter 的 Channel
- Flutter 调用 原生代码
2.1 Android 端的实现
2.2 iOS 端的实现
2.3 Flutter 端的调用 - 原生代码 调用 Flutter
3.1 Flutter 端的实现
3.2 Android 和 iOS 端的调用
一,flutter Channel
1. 关于 Flutter 的 Channel
Flutter 提供了 3 种 Channel 用于 Flutter 与 原生代码做交互,分别是:
类型 | 用途 |
---|---|
MethodChannel | 用于 Flutter 与 原生平台之间函数的互相调用 |
BasicMessageChannel | 它传递的是字节数组,使用时自定义编解码器 |
EventChannel | 用于 Flutter 与 原生平台之间事件的通信 |
我们可以借助 MethodChannel 实现 Flutter 与原生代码的相互调用。
2. 如何在 Flutter 中调用原生代码
在 Flutter 中调用原生代码,需要在原生代码中创建一个 MethodChannel
,并对这个 channel 对象设置 MethodCallHandler
即可。
每个 channel 都可以处理多个方法的调用,在 handler 对象中根据方法名做分发即可。
2.1 在 Android 端的实现 MethodChannel
Android 端需要在恰当的时机获取到 FlutterEngine
对象,例如在 FlutterActivity
的 configureFlutterEngine
方法中获取。
接着再创建 MethodChannel 通道实例,最后对通道设置 MethodCallHandler 即可:
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity: FlutterActivity() {
/* ======================================================= */
/* Override/Implements Methods */
/* ======================================================= */
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
val messenger = flutterEngine.dartExecutor.binaryMessenger
// 新建一个 Channel 对象
val channel = MethodChannel(messenger, "your_channel_name")
// 为 channel 设置回调
channel.setMethodCallHandler { call, res ->
// 根据方法名,分发不同的处理
when(call.method) {
"your_method_name" -> {
// 获取传入的参数
val msg = call.argument<String>("msg")
Log.i("ZHP", "正在执行原生方法,传入的参数是:「$msg」")
// 通知执行成功
res.success("这是执行的结果")
}
else -> {
// 如果有未识别的方法名,通知执行失败
res.error("error_code", "error_message", null)
}
}
}
}
}
2.2 在 iOS 端的实现 MethodChannel
iOS 端创建 MethodChannel 的方式和 Android 类似。 不过在 MethodCallHandler 中获取传入的参数和 Android 有差别,并且 FlutterResult 不支持像 Android 那样标记为 success/error :
class MainViewController: FlutterViewController {
/* ======================================================= */
/* Override/Implements Methods */
/* ======================================================= */
override func viewDidLoad() {
super.viewDidLoad()
// 注册渠道
let channel = FlutterMethodChannel(name: "your_channel_name", binaryMessenger: self.binaryMessenger)
channel.setMethodCallHandler { (call, res) in
// 根据函数名做不同的处理
switch(call.method) {
case "your_method_name":
yourMethodName(call, res)
default:
res(nil)
}
}
}
/* ======================================================= */
/* Private Methods */
/* ======================================================= */
private func yourMethodName(call: FlutterMethodCall, result: FlutterResult ) {
// 获取传入的参数字典
let params = call.arguments as? NSDictionary
var msg = ""
if (params != nil) {
// 获取具体的参数值
msg = params!["msg"] as? String ?? ""
}
// 打印日志
print("正在执行原生方法,传入的参数是:" + msg)
// 通知结束
result(nil)
}
}
2.3 Dart 端的调用
最后我们在 Dart 中调用原生代码中的函数,通过建立一个名称相同的 channel,调用 channel 的 invokeMethod 即可:
// 创建渠道
const channel = const MethodChannel("your_channel_name");
void callNativeMethod(String msg) {
try {
// 通过渠道,调用原生代码代码的方法
Future future = channel.invokeMethod("your_method_name", {"msg": msg} );
// 打印执行的结果
print(future.toString());
} on PlatformException catch(e) {
print(e.toString());
}
}
3. 如何在原生代码中调用 Flutter 中的方法
有些时候,例如原生组件需要回调到 Flutter 中,需要在原生代码中调用 Flutter 的函数。方法还是通过建立 Channel 对象,为 channel 设置 MethodCallHandler,再在原生代码中通过同名 channel 的 invokeMethod 调用即可。
3.1 在 Flutter 中创建 channel 并实现 MethodCallHandler
void _initChannel() {
var channel = MethodChannel("your_channel_name");
channel.setMethodCallHandler((call) {
// 同样也是根据方法名分发不同的函数
switch(call.method) {
case "your_method_name": {
String msg = call.arguments["msg"];
print("Native 调用 Flutter 成功,参数是:$msg");
return "成功";
}
}
return null;
});
}
3.2 在 Android 和 iOS 端调用 Flutter 的方法
通过创建同名 channel,并执行 invokeMethod 方法,即可在原生代码中调用 Flutter 的方法了:
Android:
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity: FlutterActivity() {
/* ======================================================= */
/* Override/Implements Methods */
/* ======================================================= */
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
val messenger = flutterEngine.dartExecutor.binaryMessenger
// 新建一个 Channel 对象
val channel = MethodChannel(messenger, "your_channel_name")
// 调用 Flutter 中的方法
val params = mapOf(
"msg" to "这是来自 Android 端的参数"
)
channel.invokeMethod("your_method_name", params)
}
}
iOS:
class MainViewController: FlutterViewController {
/* ======================================================= */
/* Override/Implements Methods */
/* ======================================================= */
override func viewDidLoad() {
super.viewDidLoad()
// 创建渠道
let channel = FlutterMethodChannel(name: "your_channel_name", binaryMessenger: self.binaryMessenger)
// 通过渠道调用 Flutter 的方法
var params: Dictionary<String, String> = ["msg": "这是来自 iOS 端的参数"]
channel.invokeMethod("your_method_name", arguments: params)
}
}
4.获取电量 来源于flutter官方教程
flutter端
static const platform = MethodChannel('samples.flutter.dev/battery');
var model = CollectFollowViewModel();
String _batteryLevel = 'Unknown battery level.';
Future<void> _getBatteryLevel() async {
String batteryLevel;
try {
final result = await platform.invokeMethod<int>('getBatteryLevel');
batteryLevel = ' $result % .';
} on PlatformException catch (e) {
batteryLevel = "Failed to get battery level: '${e.message}'.";
}
setState(() {
_batteryLevel = batteryLevel;
});
}
android端
package com.example.flutterpro.liang_flutter
import android.os.Bundle
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import org.devio.flutter.splashscreen.SplashScreen
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
class MainActivity: FlutterActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
// SplashScreen.show(this)
// or enable full screen
SplashScreen.show(this, true)
super.onCreate(savedInstanceState)
}
private val CHANNEL = "samples.flutter.dev/battery"
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
call, result ->
if (call.method == "getBatteryLevel") {
val batteryLevel = getBatteryLevel()
if (batteryLevel != -1) {
result.success(batteryLevel)
} else {
result.error("UNAVAILABLE", "Battery level not available.", null)
}
} else {
result.notImplemented()
}
}
}
private fun getBatteryLevel(): Int {
val batteryLevel: Int
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
} else {
val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
}
return batteryLevel
}
}
二,使用pigeon
以下代码均来自官网
添加pigeon依赖
在根文件下面,同lib目录同级别新建文件夹pigeons,并新建文件messages.dart,如下图
并在文件中写入如下,生成路径要看自己的具体路径
import 'package:pigeon/pigeon.dart';
//运行 flutter pub run pigeon --input pigeons/messages.dart
// flutter gen-l10n
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/pigeons/messages.dart',
dartOptions: DartOptions(),
// cppOptions: CppOptions(namespace: 'pigeon_example'),
// cppHeaderOut: 'windows/runner/messages.g.h',
// cppSourceOut: 'windows/runner/messages.g.cpp',
// gobjectHeaderOut: 'linux/messages.g.h',
// gobjectSourceOut: 'linux/messages.g.cc',
// gobjectOptions: GObjectOptions(),
kotlinOut:
'android/app/src/main/kotlin/com/example/flutterpro/liang_flutter/Messages.g.kt',
kotlinOptions: KotlinOptions(),
// javaOut: 'android/app/src/main/java/io/flutter/plugins/Messages.java',
// javaOptions: JavaOptions(),
swiftOut: 'ios/Runner/Messages.g.swift',
swiftOptions: SwiftOptions(),
// objcHeaderOut: 'macos/Runner/messages.g.h',
// objcSourceOut: 'macos/Runner/messages.g.m',
// Set this to a unique prefix for your plugin or application, per Objective-C naming conventions.
// objcOptions: ObjcOptions(prefix: 'PGN'),
// copyrightHeader: 'pigeons/copyright.txt',
// dartPackageName: 'pigeon_example_package',
))
//This is the Pigeon file that describes the interface that will be used to call from //Flutter to the host-platform.
enum Code { one, two }
class MessageData {
MessageData({required this.code, required this.data});
String? name;
String? description;
Code code;
Map<String?, String?> data;
}
@HostApi()
abstract class ExampleHostApi {
String getHostLanguage();
// These annotations create more idiomatic naming of methods in Objc and Swift.
@ObjCSelector('addNumber:toNumber:')
@SwiftFunction('add(_:to:)')
int add(int a, int b);
@async
bool sendMessage(MessageData message);
}
然后执行
flutter pub run pigeon --input pigeons/messages.dart
坑点:因为我的代码做了国际化,所以执行后会无法引入国际化
dart页面的代码
final ExampleHostApi _api = ExampleHostApi();
/// Calls host method `add` with provided arguments.
Future<int> add(int a, int b) async {
try {
return await _api.add(a, b);
} catch (e) {
// handle error.
return 0;
}
}
/// Sends message through host api using `MessageData` class
/// and api `sendMessage` method.
Future<bool> sendMessage(String messageText) {
final MessageData message = MessageData(
code: Code.one,
data: <String?, String?>{'header': 'this is a header'},
description: 'uri text',
);
try {
return _api.sendMessage(message);
} catch (e) {
// handle error.
return Future<bool>(() => true);
}
}
安卓页面(kotlin) MainActivity是我们要编写的页面,下面的Messages.g.kt是生成的,无须动他
import android.os.Bundle
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import org.devio.flutter.splashscreen.SplashScreen
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import ExampleHostApi
import FlutterError
import MessageData
import MessageFlutterApi
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugins.pathprovider.Messages
// #docregion kotlin-class
private class PigeonApiImplementation : ExampleHostApi {
override fun getHostLanguage(): String {
return "Kotlin"
}
override fun add(a: Long, b: Long): Long {
if (a < 0L || b < 0L) {
throw FlutterError("code", "message", "details")
}
return a + b
}
override fun sendMessage(message: MessageData, callback: (Result<Boolean>) -> Unit) {
if (message.code == Code.ONE) {
callback(Result.failure(FlutterError("code", "message", "details")))
return
}
callback(Result.success(true))
}
}
// #enddocregion kotlin-class
// #docregion kotlin-class-flutter
private class PigeonFlutterApi {
var flutterApi: MessageFlutterApi? = null
constructor(binding: FlutterPlugin.FlutterPluginBinding) {
flutterApi = MessageFlutterApi(binding.getBinaryMessenger())
}
fun callFlutterMethod(aString: String, callback: (Result<String>) -> Unit) {
flutterApi!!.flutterMethod(aString) { echo -> callback(echo) }
}
}
// #enddocregion kotlin-class-flutter
class MainActivity : FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
// SplashScreen.show(this)
// or enable full screen
SplashScreen.show(this, true)
super.onCreate(savedInstanceState)
}
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
val api = PigeonApiImplementation()
ExampleHostApi.setUp(flutterEngine.dartExecutor.binaryMessenger, api)
}
}