1、dart与原生交互-MethodChannel
1.1、Android
MethodChannel的两参构造MethodChannel(BinaryMessenger messenger, String name)要求传一个BinaryMessenger 类型的参数,网上很多老版本方法例如用registrar.messenger()或FlutterActivity的flutterView属性等都已经过时,目前1.17.5应使用:
val methodChannel = MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, "Flutter_Demo_Method")
不知道后面版本还会不会改,使用一些老教材学习时用新的SDK真的很难受······
onMethodCall的处理好像没变:
override fun onMethodCall(methodCall: MethodCall, channelResult: MethodChannel.Result) {
when (methodCall.method) {
"updateApp" -> {
val str = methodCall.argument<String>("str")!!
val num = methodCall.argument<Int>("num")!!
val bool = methodCall.argument<Boolean>("bool")!!
val json = methodCall.argument<String>("userInfo")!!
val userInfo = Gson().fromJson<UserInfo>(json, UserInfo::class.java)
// channelResult.success("failure")
val hashMap = HashMap<String, Any?>()
hashMap["resultCode"] = 200
hashMap["resultMsg"] = "success"
channelResult.success(hashMap)
}
else -> {
channelResult.notImplemented()
}
}
}
1.2、iOS
逻辑与Android差不多,就区别在语法上,特别是从FlutterMethodCall读取入参,iOS这边没有argument,只有arguments,所以需要将参数列表转为NSDictionary再去解析需要的参数值
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let methodChannel : FlutterMethodChannel = FlutterMethodChannel.init(name: "ECS_Personal_Method", binaryMessenger: controller.binaryMessenger)
methodChannel.setMethodCallHandler({(call:FlutterMethodCall, result: FlutterResult) -> Void in
let agrs = call.arguments as! NSDictionary
switch call.method {
case "updateApp" :
let str= agrs["str"] as! String
let num= agrs["num"] as! Int
let json = agrs["userInfo"] as! NSDictionary
result("")
default:
result(FlutterMethodNotImplemented)
}
})
2、webview_flutter插件
webview_flutter插件在iOS上使用时需要在Info.plist里加入
<key>io.flutter.embedded_views_preview</key>
<true/>
如果访问http地址,还需要加
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
但是用xcode打开iOS项目去编辑,应该是要这样:
如果全部按照AS里的key去写,最终没有效果。