Flutter项目中,调用iOS代码步骤:(共三步)
1.flutter代码中,添加MethodChannel
2.flutter代码中,调用iOS方法获取想要的值,关键词:.invokeMethod
3.iOS的AppDelegate里面FlutterMethodChannel、setMethodCallHandler 返回需要的值。
class _MixPageState extends State<MixPage> {
// 第一步添加 MethodChannel
static const plantform = MethodChannel("test.flutter.io/testAction1");
// 获取iOS代码的返回值
String iosResultString = "";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("混合开发测试"),
),
body: Center(
child: Column(
children: [
buildButton(),
Text("获取iOS结果为:${iosResultString}", style: TextStyle(fontSize: 26),)
],
),
),
);
}
Widget buildButton() {
return MaterialButton(onPressed:
() {
setState(() {
testAction1();
});
},
child: Text("获取调用iOS代码结果", style: TextStyle(fontSize: 30),),
color: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
elevation: 0,
);
}
// 调用iOS代码
Future testAction1() async {
String result = await plantform.invokeMethod("testAction1");
print("获取iOS结果:====${result}");
setState(() {
iosResultString = result;
});
}
}
iOS中添加代码:
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// flutter调用iOS的代码,在这里写。 ----- BEGIN
if let controller = window.rootViewController as? FlutterBinaryMessenger {
let channel = FlutterMethodChannel.init(name: "test.flutter.io/testAction1", binaryMessenger: controller);
channel.setMethodCallHandler { (call: FlutterMethodCall, result: FlutterResult) -> Void in
if (call.method == "testAction1") {
result("ios假数据"); // 根据需求,调用具体方法返回特定数据.
}
result(FlutterMethodNotImplemented);
}
}
// flutter调用iOS的代码,在这里写。 ----- END
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
网友评论