Flutter开发Flutter与原生OC、Java的交互通信-2(48)

我们上一篇主要讲了Flutter与原生OC、Java的交互通信的机制:平台通道
只实现了Flutter 主动调用OC、Java的方向的通信。并没有实现OC、Java端主动调用Flutter的实现。这里补充一下。

原生如何调用Flutter

当我们完成分享时,我们可能需要将分享结果传回Flutter。有同学可能会说,上面我们已经学习了Result(FlutterResult),可以通过result实现啊。但微信的这些回调是异步的,我们也不能够长期持有Result对象,所以这个时候我们要在原生中调用Flutter
原理也一样,在原生代码中,我们也有一个MethodChannel

OC 端:

#import "ViewController.h"
#import <Flutter/Flutter.h>
#include "GeneratedPluginRegistrant.h"
#import "SettingViewController.h"

@interface ViewController ()
{
    FlutterViewController *flutterVC;
    FlutterMethodChannel *batteryChannel;
}
@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.title = @"我是iOS 页面";
    
    flutterVC = [[FlutterViewController alloc]initWithProject:nil nibName:nil bundle:nil];
    flutterVC.title = @"我是Flutter页面";
    batteryChannel = [FlutterMethodChannel methodChannelWithName:@"samples.flutter.dev/battery" binaryMessenger:flutterVC];
}


- (IBAction)pushNext:(id)sender {
    NSLog(@"你好吗?");
    [self.navigationController pushViewController:flutterVC animated:YES];
    
    __weak typeof(self) weakSelf = self;
    [batteryChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
        // Note: this method is invoked on the UI thread.
        if ([@"getBatteryLevel" isEqualToString:call.method])
        {
            int batteryLevel = [weakSelf getBatteryLevel];
            if (batteryLevel == -1) {
                result([FlutterError errorWithCode:@"UNAVAILABLE" message:@"Battery info unavailable" details:nil]);
            } else {
                result(@(batteryLevel));
            }
            
        } else if ([@"backToNavigatorIndex" isEqualToString:call.method]) {
            NSArray *arguments = call.arguments;
            
            NSNumber *inde = arguments[0];
            NSLog(@"arguments :%@",inde);
            int batteryLevel = [weakSelf backToNavigatorIndex:inde];
            result(@(batteryLevel));
        } else {
            result(FlutterMethodNotImplemented);
        }
    }];
}


- (IBAction)passArgusToFlutter:(id)sender {

    NSLog(@"passArgusToFlutter");
    [batteryChannel invokeMethod:@"passArgusToFlutter" arguments:@[@12,@"huahua"] result:^(id  _Nullable result) {
        NSString *ggg = (NSString *)result;
        NSLog(@"result----:%@",ggg);
    }];
}


- (int)getBatteryLevel {
    NSLog(@"nihao!!!!!");    
    SettingViewController *settingVC = [[SettingViewController alloc]init];
    [flutterVC.navigationController pushViewController:settingVC animated:YES];
    
    return 66;
}



Flutter端:

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

class FirstScreen extends StatelessWidget {

  static const platform = const MethodChannel('samples.flutter.dev/battery');


  Future<void> _goOCPage() async {
    print('我要去OC 页面了');
    String batteryLevel;
    try {
      final int result = await platform.invokeMethod('getBatteryLevel');
      batteryLevel = 'Battery level at $result % .';
    } on PlatformException catch (e) {
      batteryLevel = "Failed to get battery level: '${e.message}'.";
    }

    print('调用了$batteryLevel');
  }

  Future<void> _goSomePage() async {
    print('我要去导航的指定页面了');
    String batteryLevel;
    try {
      final int result = await platform.invokeMethod('backToNavigatorIndex',[1]);
      batteryLevel = 'backSmoePahe $result % .';
    } on PlatformException catch (e) {
      batteryLevel = "Failed to backSmoePahe: '${e.message}'.";
    }

    print('back$batteryLevel');
  }



  @override
    Widget build(BuildContext context) {

      Future<dynamic> _handler(MethodCall methodCall) {
        if ("passArgusToFlutter" == methodCall.method) {
          print('methodCall-arguments:${methodCall.arguments}');
        }
        return Future.value(123);
      }
      platform..setMethodCallHandler(_handler);


      return Scaffold(
      appBar: AppBar(
        title: Text('FirstScreen 页面'),
      ),
      body: Center(
        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '自我介绍,我是flutter页面',
            ),

            FlatButton(
              child: Text("backLastPage"),
              textColor: Colors.blue,
              onPressed: (){
                Navigator.pop(context);
              },
            ),

            FlatButton(
              child: Text("goOCPage"),
              textColor: Colors.blue,
              onPressed: (){
                _goOCPage();
              },
            ),

            FlatButton(
              child: Text("backToSomePage"),
              textColor: Colors.blue,
              onPressed: (){
                _goSomePage();
              },
            ),

          ],
        ),
      ),
    );
  }
}
终端Log

在这里插入图片描述在这里插入图片描述

总结

连着上一篇
Flutter开发Flutter与原生OC、Java的交互通信(47)
就把Flutter与原生OC主动通信都实现了一下。填补了Flutter与原生OC主动通信这方面的知识。Flutter与原生OC、Java的交互通信用法基本结束了。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值