-
系列文章
flutter与原生交互传值OC/java版(一)
flutter与原生交互传值OC/java版(二)
四步实现flutter显示iOS原生组件OC/java版(三)
四步实现flutter显示安卓原生组件OC/java版(三)
本demo的github地址:https://github.com/iBinbro/flutterstudy
上一篇flutter plugin之路:flutter与原生交互传值OC/java版(一)说道如何使用flutter调用原生api传值(值的传递流程这样:flutter->原生->flutter,flutter调用原生方法,此时flutter可以传一个参数给原生,然后原生接受flutter的调用后,再返回一个值给flutter),这一篇说的是原生如何主动传值给flutter
实现流程
flutter通过标识监听指定的通道->原生通过这个通道向flutter发送信息->flutter通过监听这个通道获取原生发送的信息
实现目标,原生每1秒调用一次方法,自增数值,然后传到flutter,再由flutter进行显示
本demo的github地址:https://github.com/iBinbro/flutterstudy
(补充了安卓java版,以OC为例作为分析,安卓java同理不做叙述了)
一、flutter端的实现
1.创建TwoCommunicate类(statefulwidget)
2.flutter注册监听通道
3.声明两个方法用于处理接收到的数据以及异常错误
4.执行监听
5.build方法实现布局,将返回的数据显示出来
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
class TwoCommunicate extends StatefulWidget {
@override
_TwoCommunicateState createState() => _TwoCommunicateState();
}
class _TwoCommunicateState extends State<TwoCommunicate> {
//****************原生主动调用flutter****************//
//存放原生传给flutter的值
String _nativeToFlutterString = '';
//注册监听原生通道
EventChannel eventChannel = EventChannel('https://www.jianshu.com/p/7dbbd3b4ce32');
//监听到数据后用于处理数据的方法,这个函数是用于处理接收到原生传进来的数据的,可自行定义
void _receiveFromeNative(Object para){
print(para);
setState(() {
_nativeToFlutterString = para.toString();
});
}
//原生返回错误信息
void _fromNativeError(Object error){
print(error);
}
@override
void initState() {
// TODO: implement initState
//实现通道的监听,并传入两个带有参数的函数用于监听到数据后 对数据进行处理
eventChannel.receiveBroadcastStream().listen(_receiveFromeNative, onError: _fromNativeError);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('text'),
),
body: Container(
padding: EdgeInsets.all(32.0),
child: Center(
child: Column(
children: <Widget>[
//显示原生传过来的值
MaterialButton(
color: Colors.green,
child: Text(_nativeToFlutterString),
onPressed: () {
},
)
],
),
),
),
);
}
}
二、原生端iOS OC的实现,
先运行下工程,避免打开ios工程缺少文件,然后在工程目录进入ios文件夹,打开Runner.xcworkspace,使用xcode进行原生代码的编写
#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
//遵循代理方法
@interface AppDelegate()<FlutterStreamHandler>
@end
@implementation AppDelegate{
/// 用于主动传值给flutter的桥梁.
FlutterEventSink _eventSink;
NSInteger _nativeCount;
}
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
__weak __typeof(self) weakself = self;
FlutterViewController *controller = (FlutterViewController *)self.window.rootViewController;
/**********原生主动传值给flutter-Start**********/
_nativeCount = 0;
NSLog(@"原生实现 原生传值给flutter的通道标识");
FlutterEventChannel *eventChannel = [FlutterEventChannel eventChannelWithName:@"https://www.jianshu.com/p/7dbbd3b4ce32" binaryMessenger:controller];
//设置代理
[eventChannel setStreamHandler:self];
/**********原生主动传值给flutter-End**********/
[GeneratedPluginRegistrant registerWithRegistry:self];
// Override point for customization after application launch.
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
/**********原生主动传值给flutter-Start**********/
//flutter开始进行监听,并在此方法传入 原生主动传值给flutter的桥梁 event
- (FlutterError *)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)events{
NSLog(@"flutter开始进行监听,并在此方法传入 原生主动传值给flutter的桥梁 event");
_eventSink = events;
[self repeatAddNativeCount];
return nil;
}
//翻了下官方文档 Invoked when the last listener is deregistered from the Stream associated to this channel on the Flutter side. 大致意思是stream关联的这个通道监听器取消后调用,找了下flutter的dart代码,没取消监听的方法 后面再说吧 待解
- (FlutterError *)onCancelWithArguments:(id)arguments{
_eventSink = nil;
return nil;
}
- (void)repeatAddNativeCount{
NSLog(@"重复传值执行");
_nativeCount++;
//通过桥梁传值
if (_eventSink) {
_eventSink(@(_nativeCount));
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self repeatAddNativeCount];
});
}
/**********原生主动传值给flutter-Start**********/
@end
效果图