Flutter_iOS混合開(kāi)發(fā)

iOS項(xiàng)目最終是要打包上線(xiàn),上線(xiàn)后的代碼我們動(dòng)都不敢動(dòng),可能是動(dòng)不了吧,尷尬……。然而Flutter應(yīng)用也是不可以的??,帶有Flutter工程的iOS項(xiàng)目,模擬器測(cè)試的時(shí)候才可以對(duì)Flutter業(yè)務(wù)做熱更新(其實(shí)也不是熱更新)。下面就完成一個(gè)簡(jiǎn)單的iOS-Flutter交互項(xiàng)目。

參考:《Flutter環(huán)境配置》《Xcode配置》

1、創(chuàng)建一個(gè)flutter_module工程

module.png

2、創(chuàng)建混合開(kāi)發(fā)的iOS工程
3、引入pod,創(chuàng)建Podfile文件添加內(nèi)容

platform :ios, '9.0'
use_frameworks!
flutter_application_path = '../flutter_module/'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')

target 'navDemo' do
  install_all_flutter_pods(flutter_application_path)
end
target 'navDemoTests' do
  install_all_flutter_pods(flutter_application_path)
end

執(zhí)行安裝命令即可:

pod install
pod.png

重新打開(kāi)工程。

4、禁用掉工程的bitcode
targets -> Build Settings -> Enable Bitcode 設(shè)置為No
要運(yùn)行Flutter頁(yè)面,需要禁用掉Bitcode,Flutter頁(yè)面不支持Bitcode

Enable Bitcode:在應(yīng)用商店上,設(shè)置了Bitcode的應(yīng)用可以被轉(zhuǎn)換為任意CPU上的可執(zhí)行程序。

5、設(shè)計(jì)Flutter腳本
找到本地安裝Flutter目錄下的flutter_tools->bin->xcode_backend.sh腳本。這個(gè)腳本用來(lái)在Xcode編譯的時(shí)候?qū)?code>Flutter代碼也進(jìn)行編譯。
TARGETS -> Build Phases中新建腳本,并添加路徑:

"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed
xcode_backend.png

Xcode中編譯是按照Build Phases下的列表順序編譯的,Flutter官方提出腳本需要放在Target Dependences下。編譯因此需要將Run Script拖動(dòng)到第二位:

path.png

編譯一下,編譯通過(guò)。

6、在iOS工程中設(shè)置Flutter頁(yè)面
引入Flutter頭文件,并創(chuàng)建FlutterViewController。設(shè)置初始化路由,即要顯示的Flutter頁(yè)面。

@implementation ViewController
@property (nonatomic,strong)FlutterViewController *vc;
- (void)viewDidLoad {
    [super viewDidLoad];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    vc = [[FlutterViewController alloc] init];
    [vc setInitialRoute:@"one"];
    [self presentViewController:vc animated:NO completion:nil];
}
@end

運(yùn)行點(diǎn)擊屏幕即可顯示Flutter頁(yè)面,setInitalRoute是設(shè)置要顯示的頁(yè)面,向Flutter發(fā)送路由,在Flutter中接收消息后加載相應(yīng)的界面。當(dāng)前會(huì)打印flutter: null,說(shuō)明Flutter工程中沒(méi)有配置路由。

7、配置Flutter路由
Fluttermain.dart文件中引入dart:ui頭文件
runAppMyApp中添加method屬性,在widget中定義method屬性,用來(lái)傳入路由信息。
代碼如下:

import 'package:flutter/material.dart';
import 'dart:ui';

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

class MyApp extends StatelessWidget {
  final String method;

  const MyApp({Key key, this.method}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        backgroundColor: Colors.white
      ),
      color: Colors.yellow,
      home: rootPage(method),
    );
  }
}

Widget rootPage(String method){
  print(method);
  if(method=='one'){
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: Container(
          child: Text("混合開(kāi)發(fā)one",style: TextStyle(fontSize: 30),),
        ),
      )
    );
  }else {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: Container(
          child: Text("混合開(kāi)發(fā)other",style: TextStyle(fontSize: 30),),
        ),
      )
    );
  }
}

此時(shí)在運(yùn)行xcode就會(huì)打印flutter: one。

8、Xcode上通過(guò)設(shè)置不同的路由進(jìn)入不同的Flutter頁(yè)面
代碼如下:

#import "ViewController.h"
#import <Flutter/Flutter.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"混合開(kāi)發(fā)";
    self.view.backgroundColor = [UIColor whiteColor];
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake((width-200)/2, 200, 200, 40)];
    [button setTitle:@"進(jìn)入第一個(gè)頁(yè)面" forState:UIControlStateNormal];
    button.backgroundColor = [UIColor grayColor];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(btn:) forControlEvents:UIControlEventTouchUpInside];
    
    button = [[UIButton alloc] initWithFrame:CGRectMake((width-200)/2, 280, 200, 40)];
    [button setTitle:@"進(jìn)入第二個(gè)頁(yè)面" forState:UIControlStateNormal];
    button.backgroundColor = [UIColor grayColor];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(btn:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)btn:(UIButton *)button{
    FlutterViewController *vc = [[FlutterViewController alloc] init];
    if ([button.titleLabel.text isEqualToString:@"進(jìn)入第一個(gè)頁(yè)面"]) {
        [vc setInitialRoute:@"one"];
    }else{
        [vc setInitialRoute:@"other"];
    }
    [self.navigationController pushViewController:vc animated:YES];
}
@end

通過(guò)setInitialRoute告訴Flutter需要進(jìn)入的頁(yè)面。運(yùn)行結(jié)果:

ios_flutter.gif

9、Flutter調(diào)用OC代碼
導(dǎo)入services.dart頭文件,添加方法調(diào)用代碼:

MethodChannel('one_page').invokeMapMethod('popview','');

觸發(fā)該方法,即可想OC發(fā)送消息。
在Xcode代碼中添加方法通道,監(jiān)聽(tīng)Flutter消息:

//Flutter通訊,調(diào)用OC方法
FlutterMethodChannel *methodChannel = [FlutterMethodChannel methodChannelWithName:@"one_page" binaryMessenger:vc];
__weak typeof(self) weakSelf = self;
[methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
    NSLog(@"method:%@",call.method);
    NSLog(@"arguments:%@",call.arguments);
    [weakSelf.navigationController popViewControllerAnimated:YES];
}];

當(dāng)Flutter觸發(fā)MethodChannel方法,將會(huì)調(diào)用OC中的方法監(jiān)聽(tīng)block,從而達(dá)到Flutter->OC通訊的目的。

10、OC通過(guò)MethodChannel調(diào)用Flutter方法
在開(kāi)發(fā)中我們只使用一個(gè)vc即可,通過(guò)FlutterMethodChannel來(lái)調(diào)用Flutter方法來(lái)重新加載頁(yè)面。

Flutter中方法監(jiān)聽(tīng):

//設(shè)置頁(yè)面通道
final MethodChannel _pageChannel = MethodChannel("page_method");
String _method = 'one';
@override
void initState() {
  // TODO: implement initState
  super.initState();
  //頁(yè)面監(jiān)聽(tīng)OC調(diào)用方法
  _pageChannel.setMethodCallHandler((MethodCall call){
    _method = call.method;
    setState(() {});
  });
}

OC中配置:

-(void)btn:(UIButton *)button{
    self.vc.title = button.titleLabel.text;
    FlutterMethodChannel *methodChannel = [FlutterMethodChannel methodChannelWithName:@"page_method" binaryMessenger:self.vc];
    //Flutter通訊,調(diào)用OC方法
    if ([button.titleLabel.text isEqualToString:@"進(jìn)入第一個(gè)頁(yè)面"]) {
        //監(jiān)聽(tīng)page方法
        [methodChannel invokeMethod:@"one" arguments:@"arg"];//方法名+參數(shù)
    }else{
        [methodChannel invokeMethod:@"two" arguments:@"arg"];//方法名+參數(shù)
    }
    __weak typeof(self) weakSelf = self;
    [methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
        NSLog(@"method:%@",call.method);
        NSLog(@"arguments:%@",call.arguments);
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    [self.navigationController pushViewController:self.vc animated:YES];
}

除了setInitialRoute、FlutterMethodChannel可以進(jìn)行交互還有FlutterBasicMessageChannel也可以進(jìn)行交互。

通過(guò)以上幾種方法,OCFlutter之間的通訊就可以實(shí)現(xiàn)了。Flutter還不支持熱更新,只有在本機(jī)模擬器上才有熱更新的效果-修改Flutter代碼(設(shè)置顏色)模擬器重新進(jìn)入頁(yè)面,頁(yè)面顏色發(fā)生改變。

常用方法使用及說(shuō)明:

1、初始化Flutter控制器,加載Flutter頁(yè)面

_vc = [[FlutterViewController alloc] init];

2、FlutterMethodChannel的OC、Flutter交互
OC:

//初始化方法通道
_methodChannel = [FlutterMethodChannel methodChannelWithName:@"page_method" binaryMessenger:self.vc];
//向Flutter發(fā)送消息,方法名+參數(shù)
[self.methodChannel invokeMethod:@"one" arguments:@"arg”];
//接收Flutter發(fā)送的消息
[self.methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
    NSLog(@"method:%@",call.method);
    NSLog(@"arguments:%@",call.arguments);
}];

Flutter:

//初始化方法通道參數(shù)name與OC保持一致
final MethodChannel _pageChannel = MethodChannel("page_method”);
//監(jiān)聽(tīng)OC發(fā)送的消息
_pageChannel.setMethodCallHandler((MethodCall call){
  _method = call.method;
  setState(() {});
});
//像OC發(fā)送消息,方法名+參數(shù)
_pageChannel.invokeMapMethod('page','arg1');

3、MessageChannel的OC、Flutter交互
OC:

_msgChannel = [FlutterBasicMessageChannel messageChannelWithName:@"messageChannel" binaryMessenger:self.vc];
//向flutter發(fā)送消息
[self.msgChannel sendMessage:@"I am pitt"];
//接收Flutter消息
[_msgChannel setMessageHandler:^(id  _Nullable message, FlutterReply  _Nonnull callback) {
    NSLog(@"接收f(shuō)lutter發(fā)送過(guò)來(lái)的消息:%@",message);
}];

Flutter:

//持續(xù)消息發(fā)送與接收,OC對(duì)應(yīng)的name參數(shù)需要和當(dāng)前name保持一致
final BasicMessageChannel _messageChannel = BasicMessageChannel("messageChannel", StandardMessageCodec());
//向OC發(fā)送一條消息
_messageChannel.send("I am hibo");
//接收OC發(fā)送的消息
_messageChannel.setMessageHandler((message){
  print(message);
}
完整的測(cè)試代碼:https://gitee.com/yahibo/flutter_ios.git
仿微信Flutter工程:https://gitee.com/yahibo/we_chat_demo.git
weChat1.gif
weChat2.gif
weChat3.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容