Flutter插件开发(三):EventChannel
EventChannel本质上还是MethodChannel,只是封装过了.它是单向通道,只能是从原生平台向flutter端发送消息.
我们在上一章内容的基础上,继续添加代码,实现EventChannel通道的交互.
Android端PluginDevPlugin文件
1.实例化EventChannel,并且设置StreamHandler,见下图红框中代码:
2.实现streamHandler
private final EventChannel.StreamHandler streamHandler = new EventChannel.StreamHandler() {
@Override
public void onListen(Object arguments, EventChannel.EventSink events) {
eventSink = events;
cdTimer = new CountDownTimer(seconds,1000) {
@Override
public void onTick(long millisUntilFinished) {
eventSink.success(millisUntilFinished);
}
@Override
public void onFinish() {
eventSink.endOfStream();
}
} ;
cdTimer.start();
}
@Override
public void onCancel(Object arguments) {
eventSink = null;
cdTimer.cancel();
}
};
Flutter端
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class EventChannelPage extends StatefulWidget {
const EventChannelPage({Key? key}) : super(key: key);
@override
_EventChannelPageState createState() => _EventChannelPageState();
}
class _EventChannelPageState extends State<EventChannelPage> {
StreamSubscription? _streamSubscription;
String _platformMessage = '未收到消息';
final EventChannel _channel = const EventChannel('event_channel');
@override
void initState() {
// TODO: implement initState
super.initState();
_enableEventReceiver();
}
void _enableEventReceiver() {
_streamSubscription = _channel.receiveBroadcastStream().listen(
(dynamic event) {
num s = 0;
if(event is num) s = event;
setState(() {
_platformMessage = (s/1000).ceil().toString()+'s';
});
},
onError: (dynamic error) {
setState(() {
_platformMessage = error.message;
});
},
cancelOnError: true,
onDone: (){
setState(() {
_platformMessage = '完成了';
});
}
);
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
_streamSubscription?.cancel();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('EventChannel')),
body: Container(
margin:const EdgeInsets.only(top: 30,left: 15),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('原生返回的字符串:'),
Text(_platformMessage),
],
),
),
);
}
}
完整demo地址:https://github.com/shijia2118/flutter_platform_channel