美文网首页
iOS混编Flutter 之我见二

iOS混编Flutter 之我见二

作者: 小王在努力 | 来源:发表于2020-05-21 11:17 被阅读0次

前言

上一篇主要介绍iOS工程 和 Flutter工程编译器上的操作,那么本文就来介绍下代码上如何交互。

iOS 和Flutter界面跳转

1、iOS跳转Flutter工程

iOS跳转Flutter工程这个是最简单也是最容易的一种,我们只需在已经配置好的iOS工程(不知道怎么配置可看iOS混编Flutter 之我见一
如下操作:
头文件引入Flutter

import UIKit
import Flutter

iOS跳转代码

let vc : FlutterViewController = FlutterViewController.init();
 vc.fd_prefersNavigationBarHidden = true;//隐藏iOS工程导航栏
 self.navigationController?.pushViewController(vc, animated: true);
2、iOS跳转Flutter工程指定界面

跳转到指定界面相比上面来说会复杂一点,我们查看FlutterViewController的Api会发现,内部有这样一个方法

/**
 * Sets the first route that the Flutter app shows. The default is "/".
 * This method will guarnatee that the initial route is delivered, even if the
 * Flutter window hasn't been created yet when called. It cannot be used to update
 * the current route being shown in a visible FlutterViewController (see pushRoute
 * and popRoute).
 *
 * @param route The name of the first route to show.
 */
- (void)setInitialRoute:(NSString*)route;

这时候我们就可以用这个Api来跳转指定的界面,比如我这边route到Home
Flutter 中main.dart端代码

import 'dart:ui' as ui; // 调用window拿到route判断跳转哪个界面

void main() => runApp(jumpToRoute(ui.window.defaultRouteName));
Widget jumpToRoute(String route) {
  switch (route) {
    case 'fav':
      return Fav();//route到Fav界面
    case 'home':
      return Home();//route到home界面
    case 'detail':
      return Detail();//route到Detail界面
    default:
      return Main();//route到整个app
  }
}

Flutter中Home界面代码

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
      ),
      home:MyHomeCtrl(title: "",),
    );
  }
}
class MyHomeCtrl extends StatefulWidget{
  MyHomeCtrl({Key key, this.title}) : super(key: key);

  final String title;
  @override
  State<StatefulWidget> createState() {
    return _MyHomeState();
  }
}

接下来我们来看看iOS端的跳转代码

 let vc : FlutterViewController = FlutterViewController.init();
  vc.fd_prefersNavigationBarHidden = true;
  vc.setInitialRoute("home");
  self.navigationController?.pushViewController(vc, animated: true);
3、iOS跳转Flutter工程指定界面并发送数据

其实3和4很多时候是合在一起的这边为了方便大家理解把他们分开讲,为了方便理解我画了一个图如下。


iOS和Flutter交互图

简单讲就是跳转Flutter界面的时候发送一组字典数据,Flutter收到这组数据的时候去请求数据。这是3,我们来看看代码上的实现。
iOS中跳转的代码实现

let vc : FlutterViewController = FlutterViewController.init();
vc.fd_prefersNavigationBarHidden = true;
vc.setInitialRoute("detail");
let eventChannel : FlutterEventChannel = FlutterEventChannel.init(name: "com.pages.event/detail", binaryMessenger: vc.binaryMessenger);
eventChannel.setStreamHandler(self);
self.navigationController?.pushViewController(vc, animated: true);

FlutterStreamHandler协议的实现

extension GKAboutController : FlutterStreamHandler{
    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        //向flutter发送数据
        print(arguments as Any);
        let param :[String : String] = ["gender":"male","major":"玄幻"];
        events(param)
        return nil;
    }
    
    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        print(arguments as Any);
        return nil;
    }
}

Flutter中Detail界面代码
头文件引入

import 'package:flutter/services.dart';
class Detail extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
      ),
      home:DetailCtrl(title: "",),
    );
  }
}

监听数据、类似iOS中的通知(注意Channel定义要和iOS的定义一致)

  static const methodChannel = const MethodChannel('com.pages.method/detail');  //Flutter向iOS发送数据
  static const eventChannel = const EventChannel('com.pages.event/detail');//接收iOS向Flutter发送过来的数据

接收数据

  @override
  void initState(){
    super.initState();
    eventChannel.receiveBroadcastStream(1).listen(onEvent,onError: onError);
    loadData();
  }
  void onEvent(Object event) {
    Map map = event;
    String gender =  map["gender"];
    String title =  map["major"];
    widget.gender = gender;
    widget.title = title;
    loadData();
  }
  // 错误返回
  void onError(Object error) {
    print(error.toString());
  }

这时候我们就可以拿到gender和major 这两个数据的值,难后去做网络请求,获取网络数据。

4、Flutter跳转iOS工程指定界面并发送数据

通过3我们了解到了iOS想Flutter发送数据,有时候仅仅发送数据是不够的,我们还需要接收数据,所以很多时候发送数据和接收数据是联系起来的。

在上面3中Flutter定义监听我们还多定义了一个

static const methodChannel = const MethodChannel('com.pages.method/detail');  //Flutter向iOS发送数据

这个就是Flutter要向iOS发送数据的监听,我们看下Flutter是如何向iOS发送数据的,上代码
Fluttre代码实现

methodChannel.invokeMethod('detail',{"bookId":male.sId});

这里的detail有时候我们需要发送多种数据,我们就可以用这个字段区分开。

看看iOS 代码的实现

       let vc : FlutterViewController = FlutterViewController.init();
        vc.fd_prefersNavigationBarHidden = true;
        vc.setInitialRoute("detail");
        
        //iOS 向Flutter发送数据的EventChanne(EventChanne同Flutter)
        let eventName  = "com.pages.event/detail";
        let eventChannel : FlutterEventChannel = FlutterEventChannel.init(name:eventName, binaryMessenger: vc.binaryMessenger);
        eventChannel.setStreamHandler(self);
        
        //iOS 接收Flutter发送过来数据的MethodChannel(MethodChannel同Flutter)
        let methodName = "com.pages.method/detail";
        let methodChannel : FlutterMethodChannel = FlutterMethodChannel.init(name:methodName, binaryMessenger: vc.binaryMessenger);
        methodChannel.setMethodCallHandler { (call, result) in
            if call.method == "detail"{
                let json = JSON(call.arguments as Any);
                let bookId = json["bookId"].stringValue
                GKJump.jumpToDetail(bookId:bookId);
            }
            print(call.method);

            print(call.arguments as Any);
        };
        self.navigationController?.pushViewController(vc, animated: true);

看下交互效果图吧


交互.gif

以上4步基本上实现了iOS和Flutter代码交互的逻辑。

相关文章

网友评论

      本文标题:iOS混编Flutter 之我见二

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