Flutter与原生iOS交互

从Flutter项目跳转到iOS原生界面

Flutter官网镇楼

Flutter官网

前言

从Flutter项目跳转到iOS原生界面,支持push和present方式,由于时间比较紧,所以只总结了页面跳转,后续会完善flutter与原生之间的交互传值。话不多说,直接上代码(本人是iOS开发,所以Android 端暂时没有实现)

Flutter 代码

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter native iOS'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

/*<与原生交互信号通道 >*/
const methodChannel = const MethodChannel('flutter_native_ios');

class _MyHomePageState extends State<MyHomePage> {
  //封装 Flutter 向 原生中 发送消息 的方法
  //method 为方法标识
  //arguments 为参数
  static Future<dynamic> tokNative(String method, {Map arguments}) async {
    if (arguments == null) {
      //无参数发送消息
      return await methodChannel.invokeMethod(method);
    } else {
      //有参数发送消息
      return await methodChannel.invokeMethod(method, arguments);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new ListTile(
              title: new Text('flutter与原生交互,(push)'),
              trailing: FlatButton(
                  onPressed: () {
                    tokNative('flutter_push_to_ios')
                      ..then((result) {
                        print('$result');
                      });
                    print('push');
                  },
                  child: Icon(
                    Icons.arrow_forward_ios,
                    size: 20,
                  )),
            ),
            new ListTile(
              title: new Text('flutter与原生交互,(present)'),
              trailing: FlatButton(
                  onPressed: () {
                    tokNative('flutter_present_to_ios')
                      ..then((result) {
                        print('$result');
                      });
                    print('present');
                  },
                  child: Icon(
                    Icons.arrow_forward_ios,
                    size: 20,
                  )),
            ),
          ],
        ),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

iOS原生代码

一、在iOS项目里创建跟控制器,继承于FlutterViewController

 #import "MainViewController.h"
#include "GeneratedPluginRegistrant.h"
#import "TestViewController.h"

/** 信号通道,须与flutter里一致*/
#define flutterMethodChannel  @"flutter_native_ios"
/** 交互方法字段名,须与flutter里一致*/
#define flutterMethodPush  @"flutter_push_to_ios"
#define flutterMethodPresent  @"flutter_present_to_ios"

@interface MainViewController ()

@property(nonatomic,strong) FlutterMethodChannel* methodChannel;

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self methodChannelFunction];
}
- (void)methodChannelFunction {
    //创建 FlutterMethodChannel
    self.methodChannel = [FlutterMethodChannel
                          methodChannelWithName:flutterMethodChannel binaryMessenger:self];
    //设置监听
    [self.methodChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
        // TODO
        NSString *method=call.method;
        if ([method isEqualToString:flutterMethodPush]) {
            TestViewController *vc = [[TestViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            //此方法只能调用一次
            result(@"push返回到flutter");
        }else if ([method isEqualToString:flutterMethodPresent]) {
            TestViewController *vc = [[TestViewController alloc] init];
            [self presentViewController:vc animated:NO completion:nil];
            //此方法只能调用一次
            result(@"present返回到flutter");
        }
        
    }];
    [GeneratedPluginRegistrant registerWithRegistry:self];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

@end

二、APPDelegate实现方式

#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
#import "MainViewController.h"
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    /** 设置主控制器继承FlutterViewController*/
    MainViewController * VC = [[MainViewController alloc]init];
    UINavigationController * NVC = [[UINavigationController alloc]initWithRootViewController:VC];
    [self.window setRootViewController:NVC];
    /** flutter插件通道代理*/
  [GeneratedPluginRegistrant registerWithRegistry:self];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end

三、你需要跳转的控制器,普通控制器,不需要继承FlutterViewController

#import "TestViewController.h"

@interface TestViewController ()

@end

@implementation TestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    
}
-(void)initUI{
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    UIButton * btn =[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(20, 50, 50, 20);
    [btn setTitle:@"返回" forState:UIControlStateNormal];
    [btn setBackgroundColor:[UIColor grayColor]];
    [btn addTarget:self action:@selector(backEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];    
    
}
-(void)backEvent{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lester_ge

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值