Flutter学习之:iOS原生与Flutter交互

在iOS原生项目中指定路由打开Flutter页面

iOS代码

let flutterVC: FlutterViewController = FlutterViewController.init()
//指定路由跳转
flutterVC.setInitialRoute("myApp")
self.navigationController?.pushViewController(flutterVC, animated: true)

flutter代码

import 'dart:ui'; //引入头文件

void main() => runApp(MyApp(route: window.defaultRouteName));

class MyApp extends StatelessWidget {
 // This widget is the root of your application.
 final String route;
 MyApp({Key key, this.route}) : super(key: key);
 @override
 Widget build(BuildContext context) {
   return MaterialApp(
     title: 'Flutter Demo',
     theme: ThemeData(
        primarySwatch: Colors.blue,
     ),
     home: _widgetForRoute(route),
   );
  }
}

//跳转到指定页面
//通过指定路由打开Flutter的页面都需要在MaterialApp()才可以
Widget _widgetForRoute(String route) {
  switch (route) {
  case 'myApp':
    return MyHomePage();
  case 'homePage':
    return HomePage();
  default:
    return Center(child: Text('Unknown route:$route'));
  }
}

在iOS原生项目中与Flutter交互

flutter代码

static const platform = const MethodChannel('com.hehuimin.flutter/platform_method');

//Native向Flutter发送消息
 Future _invokeNativeGetResult() async {
   String backString;
   try {
     //{'key': 'From Flutter Page'}传给原生的参数
     var result = await platform.invokeMethod('getNativeResult', {'key': 'From Flutter Page'});
       backString = '原生传过来的参数:$result';
   } on PlatformException catch (e) {
       backString = 'Failed to get natvie return: ${e.message}';
   }

   setState(() {
    nativeBackString = backString;
   });
}

//flutter 注册原生监听方法
platform.setMethodCallHandler(_handleCallback);

 //Flutter向Native发送消息
 Future _handleCallback(MethodCall methodCall) {
   //这边打印的会在xCode中输出
   print('flutter:$methodCall.arguments');
   String backString = '';
   if (methodCall.method == 'sendMessage') {
     backString = 'send success';
   } else {
     backString = 'send fail';
   }
   return Future.value(backString);
 }

iOS代码

let methodChannel:FlutterMethodChannel = FlutterMethodChannel.init(name: "com.hehuimin.flutter/platform_method", binaryMessenger: flutterVC as! FlutterBinaryMessenger)

 //Native向Flutter发送消息
 methodChannel.setMethodCallHandler { [weak self] (methodCall, result) in
   guard let `self` = self else {return}
   if (methodCall.method == "getNativeResult") {
   //接收Flutter参数
   print(methodCall.arguments ?? "Not Result")
   if let arguments = methodCall.arguments as? Dictionary {
     self.label1.text = arguments["key"] as? String
   }
   //返回值给Flutter
   let name:String = UIDevice.current.name
   result(name)

   //为了方便就在这里处理了
   //Flutter向Native发送消息
   methodChannel.invokeMethod("sendMessage", arguments: ["key":"hehuimin"]) { (result) in
     print(result ?? "Not Result")
     let value: String = result as? String ?? ""
     self.label2.text = "flutter传过来的参数:" + value
   }
}

参考文章:https://www.jianshu.com/p/ca0e47ffef71

Demo地址:SwiftFlutterDemo

你可能感兴趣的:(Flutter学习之:iOS原生与Flutter交互)