博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Flutter与原生native互相通信
阅读量:4292 次
发布时间:2019-05-27

本文共 4801 字,大约阅读时间需要 16 分钟。

(本文只列出与Android Native的交互,iOS使用相同的Api,处理方式类似)。主要就是 MethodChannel的使用,因为native端和flutter端都有 methodChannel的setMethodCallHandler(),和invokeMethod()方法,所以两端都可以使用methodChannel进行通信。

Dart调用Native源码:

//Dart端源码

import 'dart:async';import 'package:flutter/material.dart';import 'package:flutter/services.dart';...class _MyHomePageState extends State
{ static const platform = const MethodChannel('samples.flutter.dev/battery'); // Get battery level.}// Get battery level. String _batteryLevel = 'Unknown battery level.'; Future
_getBatteryLevel() async { 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}'."; } setState(() { _batteryLevel = batteryLevel; }); }

//Native端,Android Java.(Kotlin类似)。交互代码运行在mainThread主线程。

import io.flutter.app.FlutterActivity;import io.flutter.plugin.common.MethodCall;import io.flutter.plugin.common.MethodChannel;import io.flutter.plugin.common.MethodChannel.MethodCallHandler;import io.flutter.plugin.common.MethodChannel.Result;public class MainActivity extends FlutterActivity {    private static final String CHANNEL = "samples.flutter.dev/battery";    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        GeneratedPluginRegistrant.registerWith(this);        new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(                new MethodCallHandler() {                    @Override                    public void onMethodCall(MethodCall call, Result result) {                        // Note: this method is invoked on the main thread.                        if (call.method.equals("getBatteryLevel")) {                            int batteryLevel = getBatteryLevel();                            if (batteryLevel != -1) {                                result.success(batteryLevel);                            } else {                                result.error("UNAVAILABLE", "Battery level not available.", null);                            }                        } else {                            result.notImplemented();                        }                    }                });    }}

 

Native发送给flutter数据:(同样使用methodChannel机制)

//native 端。这里是Kotlin,Java类似。

const val CONNECTION_CHANNEL = "com.demo.flutter.connection"val methodChannel = MethodChannel(flutterView, CONNECTION_CHANNEL)        methodChannel.setMethodCallHandler { methodCall, result ->            when (methodCall.method) {                "activityFinish" -> {                    goBack() //关闭当前页面                    result.success(null) //标识调用成功                }                "showToastMessage" -> showShortToast(methodCall.argument
("message")) } }//使用注册的方法channel调用dart端方法名称,并传递参数。 Handler().postDelayed({ methodChannel.invokeMethod("aaa", "c") }, 5000);

//dart端

static const _platform = const MethodChannel("com.whitehorse.flutter.connection");  _AboutPageState() {    _platform.setMethodCallHandler((handler) {      switch (handler.method) {        case "aaa":          _platform.invokeMethod("showToastMessage", {"message": "您调用了dart里的方法"});          break;      }    });  }  void _goBack() {//    _platform.invokeMethod("activityFinish");  }

 

另一种方式,实现native flutter通信:

基于 EventChannel,使用事件流 event stream 驱动,更适合长久耗时的方法调用。

//Native端,android.

public class MainActivity extends FlutterActivity {    public static final String STREAM = "com.yourcompany.eventchannelsample/stream";     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        new EventChannel(getFlutterView(), STREAM).setStreamHandler(                new EventChannel.StreamHandler() {                    @Override                    public void onListen(Object args, final EventChannel.EventSink events) {                        Log.w(TAG, "adding listener");                    }                    @Override                    public void onCancel(Object args) {                        Log.w(TAG, "cancelling listener");                    }                }        );    }}

//flutter,dart端

static const stream =    const EventChannel('com.yourcompany.eventchannelsample/stream');StreamSubscription _timerSubscription = null;void _enableTimer() {  if (_timerSubscription == null) {    _timerSubscription = stream.receiveBroadcastStream().listen(_updateTimer); // 添加监听  }}void _disableTimer() {  if (_timerSubscription != null) {    _timerSubscription.cancel();    _timerSubscription = null;  }}

* flutter receiveBroadcastStream([arguments]) 返回一个 broadcast stream对象。使用API进行操作。

常用的为 listener。

转载地址:http://fnegi.baihongyu.com/

你可能感兴趣的文章
年薪170万的阿里P8级员工征婚有感--话说阿里真有钱,这员工要求的条件真多
查看>>
又是一年桂花飘香时,祝我们伟大的祖国70年华诞更加繁荣昌盛,祝大家国庆节快乐
查看>>
谷歌浏览器chrome即将在2020年底停止支持flash,我们程序员该怎么办
查看>>
如何将数据采集到 Elasticsearch 服务
查看>>
面试官:mysql表设计要注意什么?
查看>>
一些精致小众网站收集录
查看>>
计算机科学探秘之linux发展史
查看>>
程序员每天早上早来10分钟的好处
查看>>
互联网30年,泡沫如梦,一个个泡沫和风口过后,会是什么样的结局
查看>>
升级centos 6.8 服务器的gcc
查看>>
API网关在微服务架构中的应用,这一篇就够了
查看>>
JVM发生内存溢出的8种原因、及解决办法
查看>>
SpringBoot2.0 基础案例(12):基于转账案例,演示事务管理操作
查看>>
高性能负载均衡:nginx搭建tomcat集群
查看>>
Spring切面中的正则表达式
查看>>
一直再说高并发,多少QPS才算高并发?
查看>>
Git恢复之前版本的两种方法reset、revert(图文详解)
查看>>
Maven打包的三种方式
查看>>
电商场景:并发扣库存,怎么保证不超卖又不影响并发性能
查看>>
分布式事务处理方式总结
查看>>