赞
踩
首先在flutter端创建信道
ios端
ElevatedButton( onPressed: () async { // const MethodChannel _channel = MethodChannel('com.example/my_channel'); try { var result = await _channel.invokeMethod('iosResponDart'); print('iOS端返回: $result'); var resJson = await _channel.invokeMethod('iosResponJson'); print('iOS端返回: $resJson'); } on PlatformException catch (e) { print('调用iOS原生接口出错: ${e.message}'); } }, child: const Text( '点击按钮', style: TextStyle(fontSize: 20.0), ), ),
在Futter项目中的文件夹下/ios/Runner/AppDelegate.swift
在该文件下AppDelegate.swift增加以下代码
楼主对swift语法不熟悉,随便写了2个返回数组和json串给dart端,成功跑通
swift的语法和dart端的语法关键是 ‘com.example/my_channel’ 这2个信道关键字要一样,然后dart端 await _channel.invokeMethod(‘iosResponJson’) 和swift 里面的call.method == "iosResponJson"这2个关键字要一样,然后再下面写你需要的函数接口就行了
import UIKit import Flutter import Foundation @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { let controller: FlutterViewController = window?.rootViewController as! FlutterViewController let methodChannel = FlutterMethodChannel(name: "com.example/my_channel", binaryMessenger: controller.binaryMessenger) methodChannel.setMethodCallHandler({ [weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in if call.method == "getPlatformVersion" { result("iOS " + UIDevice.current.systemVersion) }else if (call.method == "iosResponDart"){ result(self!.getUInt8Array()) }else if (call.method == "iosResponJson"){ result(self!.createJSON()) } else { result(FlutterMethodNotImplemented) } }) GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } func getUInt8Array() -> [UInt8] { let byteArray: [UInt8] = [0x01, 0x02, 0x03, 0x04, 0x05] return byteArray } func createJSON() -> String { // 创建一个包含一些数据的字典 let dataDict: [String: Any] = [ "name": "John Doe", "age": 30, "isStudent": false, "grades": [95, 87, 92, 87, 57] ] // 将字典转换为 JSON 数据 if let jsonData = try? JSONSerialization.data(withJSONObject: dataDict, options: []) { // 将 JSON 数据转换为字符串 if let jsonString = String(data: jsonData, encoding: .utf8) { return jsonString } } // 如果转换失败,返回一个空字符串或错误信息 return "" } }
安卓端
和ios类似,先创建通道
const platform = MethodChannel("com.example/my_channel");
int results =
await platform.invokeMethod("printSum", {"a": 5, "b": 7});
print("flutter打印原生函数输出$results");
var a = await platform.invokeMethod("responseDart");
print("dart端: $a");
var b = await platform.invokeMethod("responseJson");
print("dart端: $b");
调用安卓原生端:
楼主在下面这个路径创建的一个文件用于与安卓原生交互
android/app/src/main/kotlin/com/example/kataeapp/MainActivity.kt
package com.example.kataeapp import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel import com.example.kataeapp.AutoInstall import android.content.Context import android.content.Intent import android.provider.Settings import com.fasterxml.jackson.databind.ObjectMapper class MainActivity : FlutterActivity() { private val CHANNEL = "com.example/my_channel" override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) MethodChannel( flutterEngine.dartExecutor.binaryMessenger, CHANNEL ).setMethodCallHandler { call, result -> if (call.method == "getPlatformVersion") { val version = "Android BYLTEST" + android.os.Build.VERSION.RELEASE result.success(version) } else if (call.method == "printDocumentInit") { result.success(call.argument("test")) } else if (call.method == "autoInstall") { // A result.success(call.argument("test")) } else if (call.method == "printSum") { val a = call.argument<Int>("a") ?: 0 val b = call.argument<Int>("b") ?: 0 var sum= printSum(a,b) result.success(sum) } else if (call.method == "openSettings") { openSettings(this) // result.success(sum) } else if (call.method == "responseDart") { var a = responseDart() result.success(a) } else if (call.method == "responseJson") { var b = createJson() result.success(b) } else { result.notImplemented() } } } fun printSum(a: Int,b:Int): Int{ return a+b; } fun responseDart(): ByteArray { val uint8Array = ubyteArrayOf(0x01u, 0x02u, 0x03u, 0x04u, 0x05u) return uint8Array.toByteArray() } fun openSettings(context: Context) { val intent = Intent(Settings.ACTION_SETTINGS) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.applicationContext.startActivity(intent) } } data class Person(val name: String, val age: Int, val isStudent: Boolean, val grades: List<Int>) fun createJson(): String { // 创建一个包含一些数据的 Person 对象 val person = Person("John Doe", 30, false, listOf(95, 87, 92)) // 使用 Jackson 库将对象转换为 JSON 字符串 val objectMapper = ObjectMapper() return objectMapper.writeValueAsString(person) }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。