flutter插件开发学习之旅(6)-------双平台初始插件开发原理

前言

前段时间因为时间有限就只有弄android端的,今天腾出一些时间,终于把android和ios端的都弄出来了,准备写一篇博客供大家学习,

准备工具

这套课程是采用Android Studio和xcode进行开发的。当前在此之前请准备好Flutter开发环境,我这里就不进行讲解了。一些基础的知识,请到我的初始插件开发原理这篇博客观看构建流程

手动填写一个demo

Android端插件

在flutter_plugin.dart添加一个方法getNative

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 getNative async {
    final String sayHello = await _channel.invokeMethod('getNative');
    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.getNative;		//调用刚刚新建的方法
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

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

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

在这里插入图片描述

IOS端插件

打开ios端

在这里插入图片描述

找到原生文件 这里有点难找,大家细心找找哈

在这里插入图片描述

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

#import "FlutterPlugin1Plugin.h"

@implementation FlutterPlugin1Plugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"flutter_plugin1"
            binaryMessenger:[registrar messenger]];
  FlutterPlugin1Plugin* instance = [[FlutterPlugin1Plugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getPlatformVersion" isEqualToString:call.method]) {
    result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
  //主要是这个
  }else if([@"getNative" isEqualToString:call.method]){
      result(@"Hello Flutter plugin");
  }
  else {
    result(FlutterMethodNotImplemented);
  }
}

@end

在这里插入图片描述

通过这篇博客 大家应该都理解双平台的插件该怎么编写了,喜欢的话,记得关注我,我会持续更新的,今天就分享到这里了

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

猜你喜欢

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