美文网首页
Flutter开发与原生Android的调用

Flutter开发与原生Android的调用

作者: 我打小就帅 | 来源:发表于2020-03-24 18:17 被阅读0次

Flutter作为一套比较成熟的ui系统,基础能完成原生能做的ui,但是毕竟不能直接调用系统,比说相机,位置,地图之类的,所以这时候就要进行Flutter与原生的调用,由于本人安卓开发过来的,不会ios,所以这里只能介绍flutter开发Android的交互
效果图:

asas.png

通道Platform Channel
首先在原生层android/app的目录下建立原生层的类
1,MyCustomViewView 实现PlatformView接口创建原生视图,通实MethodChannel
接口实现对flutter传过来的数据监听。

package com.zhang.flutter_jianshu2;

import android.content.Context;
import android.view.View;
import android.widget.TextView;


import java.util.Map;

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;
 
public class MyCustomViewView implements PlatformView, MethodChannel.MethodCallHandler {
    private  TextView myNativeView;
    MyCustomViewView(Context context, BinaryMessenger messenger, int id, Map<String, Object> params) {
     myNativeView = new TextView(context);
        myNativeView.setText("我是来自Android的原生TextView");
        this.myNativeView = myNativeView;
        if (params.containsKey("myContent")) {
            String myContent = (String) params.get("myContent");
            myNativeView.setText(myContent);
        }

        MethodChannel methodChannel = new MethodChannel(messenger, "suibianzifuchuan_" + id);
        methodChannel.setMethodCallHandler(this);
    }



    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        if ("setText".equals(methodCall.method)) {
            String text = (String) methodCall.arguments;
            myNativeView.setText(text);
            result.success(null);
        }

    }

    @Override
    public View getView() {
        return myNativeView;
    }

    @Override
    public void dispose() {

    }
}

2,CustomViewRegistrant 用于在原生的监听注册,这里注册时要注意通道值要和flutter的一致,确保在同一条通道上才可以交互。

public class CustomViewRegistrant {

    private static final String TAG = CustomViewRegistrant.class.getName();

    public static void registerWith(PluginRegistry registry) {
        final String key = CustomViewRegistrant.class.getCanonicalName();
        Log.i(TAG,"registerKey="+key);
        if (registry.hasPlugin(key)) {
            return;
        }
        PluginRegistry.Registrar registrar = registry.registrarFor(key);
        registrar.platformViewRegistry().registerViewFactory("suibianzifuchuan_", new MyViewFactory(registrar.messenger()));
 
    }
}

在MainActivity中进行注册

class MainActivity: FlutterActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    GeneratedPluginRegistrant.registerWith(this)

    CustomViewRegistrant.registerWith(this)//注册
  }
}

4,flutter这边的调用

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

class PlatChannel extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return PlatChannelState();
  }
}

class PlatChannelState extends State<PlatChannel> {
 

  //2.编写页面
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter与原生界面交互"),
      ),
      body: Center(
        child: AndroidView(
          viewType: 'suibianzifuchuan_',
          creationParams: {
            "myContent": "通过参数传入的文本内容",
          },
          creationParamsCodec: const StandardMessageCodec(),
          onPlatformViewCreated: onMyViewCreated,
        ),
      ),
    );
  }

  MethodChannel _channel;

  void onMyViewCreated(int id) {
    _channel = new MethodChannel('suibianzifuchuan_$id');
    setText("哈哈哈adf");
  }

  Future<void> setText(String text) async {
    assert(text != null);
    return _channel.invokeMethod('setText', text);
  }

}

好了,在取得代码运行成功之后,不妨再深刻理解这个通讯机制,Platform Channel主要分三种:
(1)BasicMeaaspeChannel :大内存数据块传递的情况使用
(2)MethodChannel:传递方法的调用,通常情况下用
(3)EventChannel:数据流的通讯

这三种通讯在不同情况下使用,但是共同点都是通过BinaryMesage作为通讯工具。

注意事项

1,进行通道测试时,热重载是无效的
2,尽量避免对原生层的过多调用,流畅性并不是很多
3,debug模式跳转flutter调用原生页面时会出现白屏闪动的情况,但是release模式就不会。

好了,附上源码:

参考文章:
https://blog.csdn.net/zhutao_java/article/details/89916862

https://blog.csdn.net/weixin_33796177/article/details/88012429?depth_1-utm_source=distribute.pc_relevant_right.none-task&utm_source=distribute.pc_relevant_right.none-task

相关文章

网友评论

      本文标题:Flutter开发与原生Android的调用

      本文链接:https://www.haomeiwen.com/subject/zkxpshtx.html