当前位置:   article > 正文

flutter和安卓原生代码及IOS原生代码的简单通信_ios安卓 通用代码

ios安卓 通用代码

首先在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),
   ),
 ),
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

在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 ""
  } 
}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

安卓端

和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");
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

调用安卓原生端:
楼主在下面这个路径创建的一个文件用于与安卓原生交互
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)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/383247
推荐阅读
相关标签
  

闽ICP备14008679号