美文网首页
iOS集成Flutter及交互

iOS集成Flutter及交互

作者: 桔子橙子柚子_F | 来源:发表于2020-03-26 13:50 被阅读0次

    1、新建项目。注意!!!将我们项目 BitCode 选项设置为 NO , Flutter 目前还不支持。
    2、cd到工程目录下
    3、创建一个Flutter项目模块,执行:

    flutter create -t module flutter_module
    

    4、运行flutter_module,才会生成framework,显示隐藏文件拷贝 App.framework和engine 到iOS工程目录 Flutter文件夹下


    image.png

    5、将Flutter模块以pod的方式加入到项目中

    flutter_application_path = '../flutter_module'
    eval(File.read(File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')), binding)
    

    6、添加App.framework 和flutter.framework到

    Link Binary With Libraries (3 items).png

    运行如果出现dyld: Library not loaded: @rpath/Flutter.framework/Flutter……错误

    image.png

    7、controller中调用

    FlutterViewController *vc = [[FlutterViewController alloc] init];
     [self presentViewController:vc animated:YES completion:nil];
    

    8、打包时报错

    IPA processing failed

    2020-02-10 070818 +0000 warning Configuration issue platform iPhoneSimulator.platform doesn't have any non-simulator SDKs; ig.png

    因为项目中使用的SDK包含x86_64架构,iOS13苹果取消了32位系统的支持

    cd到framework下,执行

    lipo -remove x86_64 Flutter -o Flutter
    

    #############################################################

    接下来就是iOS和Flutter的交互问题了,和Android、Flutter交互一样需要依靠MethodChannel和EventChannel
    iOS代码:

        FlutterViewController *vc = [[FlutterViewController alloc] init];
        //显示哪个页面
        [vc setInitialRoute:@"secondApp"];
        [self.navigationController pushViewController:vc animated:YES];
        
       //和flutter中保持一致
        NSString *channelName = @"POP_VC";
        NSString *eventName = @"EVENT_VC";
        //ios给flutter传参
        FlutterEventChannel *eventChannel = [FlutterEventChannel eventChannelWithName:eventName binaryMessenger:vc];
        [eventChannel setStreamHandler:self];
        
        
        //flutter给ios传参数
        FlutterMethodChannel *methodChannel = [FlutterMethodChannel methodChannelWithName:channelName binaryMessenger:vc];
        [methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
            if ([call.method isEqualToString:@"iospushtovc"]) {
                //iospushtovc  
            }else if ([call.method isEqualToString:@"pushiosnewvc"]) {
                //pushiosnewvc
            }
        }];
    
    #pragma mark - FlutterStreamHandler
    //Flutter端开始监听这个channel时的回调,第二个参数 EventSink是用来传数据的载体。
    - (FlutterError *)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)events {
        self.eventSink = events;
        self.eventSink(@"传值给flutter:参数111");
        return nil;
    }
    // flutter不再接收
    -(FlutterError *)onCancelWithArguments:(id)arguments{
        self.eventSink = nil;
        return nil;
    }
    

    Flutter代码:

    void main() => runApp(_widgetForRoute(window.defaultRouteName));
    
    ///根据iOS调用时传入的参数判断显示哪个Widget
    Widget _widgetForRoute(String routeStr) {
      switch(routeStr) {
        case 'firstApp':
          return MyApp();
          break;
        case 'secondApp':
          return secondRoute();
          break;
        default:
          return tabbar();
      }
    }
    

    新建一个工具类

    class FlutterPlugin {
      static const methodChannel = const MethodChannel('POP_VC');
      static const eventChannel = const EventChannel('EVENT_VC');
      //告诉ios,需要跳转到下一页了。ios自己跳,并传给ios一个字符串
      static Future<void> backIosToVc() async{
        await methodChannel.invokeMethod('iospushtovc', '这是flutter传递的字符串');
      }
      static Future<void> pushIOSToVc() async{
        await methodChannel.invokeMethod('pushiosnewvc', '这是flutter传递的字符串');
      }
      //传给ios一个map
      static Future<void> iOSGetMap() async{
        Map map = {"code":"1", "data":[1,2,3]};
        await methodChannel.invokeMethod("iosgetmap",map);
      }
     
    }
    
    class secondRoute extends StatefulWidget{
      _secondRouteState createState() => _secondRouteState();
    }
    
    
    class _secondRouteState extends State {
      String title = "跳转到ios原生界面";
      @override
      void initState() {
        super.initState();
    //监听事件    
    FlutterPlugin.eventChannel.receiveBroadcastStream(12345).listen(_onEvent,onError:_onError);
      }
    //收到iOS的值
      void _onEvent(Object event){
        setState(() {
          title = event.toString();
        });
      }
    
      // 错误返回
      void _onError(Object error) {
    
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: "Flutter Route",
          theme: ThemeData(primaryColor: Colors.blue),
          home: Scaffold(
            body: Container(
              child: Padding(
                padding: EdgeInsets.only(top: 120, left: 60),
                child: Column(
                  children: <Widget>[
                    FlatButton(
                        onPressed: (){
                       //给iOS端传值
                          FlutterPlugin.backIosToVc();
                        },
                        child: Text("返回到ios界面  参数:" + title,style: TextStyle(color: Colors.red,fontSize: 16),)),
                    FlatButton(
                        onPressed: (){
                      //给iOS端传值
                          FlutterPlugin.pushIOSToVc();
                        }
                        , child: Text("进入ios新界面"))
                  ],
                ),
              )
            ),
          ),
        );
      }
    }
    

    相关文章

      网友评论

          本文标题:iOS集成Flutter及交互

          本文链接:https://www.haomeiwen.com/subject/qfqcuhtx.html