flutter插件开发学习之旅(1)-------初识插件开发原理

前言

大家在开发flutter项目的时候,常常遇到一个原生的api无法进行调用,我也苦心这个问题,经过大神的建议,我就去学习了Flutter插件开发,使得Flutter项目可以调用原生的api。

准备工具

这套课程是采用Android Studio进行开发的。当前在此之前请准备好Flutter开发环境,我这里就不进行讲解了

构建项目

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

项目目录介绍

在这里插入图片描述

解析插件源码

在这里插入图片描述

setMethodCallHandler 这个就是为上层服务的

在这里插入图片描述

这里面的 static const MethodChannel _channel =const MethodChannel(‘flutter_plugin’);中的id必须要和底层的final MethodChannel channel = new MethodChannel(registrar.messenger(), “flutter_plugin”);中的id一样,一定要一一对应。

在这里插入图片描述

还有采用插件方法必须要采用异步的方法,之后再main.dart,把platformVersion绑定到body Text中。

example项目之所以可以调用到flutter_plugin.dart。是因为pubspec.yaml中添加了
flutter_plugin:
path: …/

手动填写一个demo

在flutter_plugin.dart添加一个方法sayHello

class FlutterPlugin {
  static const MethodChannel _channel =
      const MethodChannel('flutter_plugin');

  static Future<String> get platformVersion async {
    final String version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  static Future<String> get sayHello async {
    final String sayHello = await _channel.invokeMethod('sayHello');
    return sayHello;
  }
}

在main.dart中,调用这个方法

Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      //platformVersion = await FlutterPlugin.platformVersion;
      platformVersion = await FlutterPlugin.sayHello;		//调用刚刚新建的方法
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

到底层方法进行编写添加一个if语句

@Override
  public void onMethodCall(MethodCall call, Result result) {
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android " + android.os.Build.VERSION.RELEASE);
    } if(call.method.equals("sayHello")){
      result.success("Hello Android ");
    }else {
      result.notImplemented();
    }
  }

在这里插入图片描述

运行成功,今天就先分享到这里了。

发布了50 篇原创文章 · 获赞 35 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_35905501/article/details/88969586