Plugin development of Flutter

1. Plugin development

  1. Open AS selection->Flutter-> ProjectType-Pluginas shown below:

image.pngProject name (my_plugin_demo_2023)

image.png

Then open libto view the dart code:

image.png

Then the code (MyPluginDemo2023Platform):


Future<String?> getPlatformVersion() {
  throw UnimplementedError('platformVersion() has not been implemented.');
}
//获取电池电量
Future<String?> getPlatformBatteryLevel() {
  throw UnimplementedError(
      'getPlatformBatteryLevel() has not been implemented.');
}

Then implement the class:

class MethodChannelMyPluginDemo2023 extends MyPluginDemo2023Platform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('my_plugin_demo_2023');

  @override
  Future<String?> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  //实现电池电量
  @override
  Future<String?> getPlatformBatteryLevel() async {
    int batteryLevel =
    await methodChannel.invokeMethod('getPlatformBatteryLevel');
    return batteryLevel.toString();
  }
}

Implementation code:

import 'my_plugin_demo_2023_platform_interface.dart';

class MyPluginDemo2023 {
  Future<String?> getPlatformVersion() {
    return MyPluginDemo2023Platform.instance.getPlatformVersion();
  }

  Future<String?> getPlatformBatteryLevel() {
    return  MyPluginDemo2023Platform.instance.getPlatformBatteryLevel();
  }
}

ios code:

import Flutter
import UIKit

public class MyPluginDemo2023Plugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "my_plugin_demo_2023", binaryMessenger: registrar.messenger())
    let instance = MyPluginDemo2023Plugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "getPlatformVersion":
      result("iOS " + UIDevice.current.systemVersion)
    case "getPlatformBatteryLevel":
        let level = getBatteryLevel()
        result(level)
    default:
      result(FlutterMethodNotImplemented)
    }
  }

    func getBatteryLevel() -> Int {
        UIDevice.current.isBatteryMonitoringEnabled = true
        let batteryLevel = UIDevice.current.batteryLevel

        if batteryLevel == -1 {
            return -1
        } else {
            return Int(batteryLevel * 100)
        }
    }
}

Android code:

override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
  if (call.method == "getPlatformVersion") {
    result.success("Android ${android.os.Build.VERSION.RELEASE}")
  } else if (call.method == "getPlatformBatteryLevel"){
    val context: Context = this
    val batteryLevel = getBatteryLevel(context.applicationContext)
    result.success("Android ${batteryLevel}")
  } else {
    result.notImplemented()
  }
}

override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
  channel.setMethodCallHandler(null)
}

fun getBatteryLevel(context: Context): Int {
  val batteryIntent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
  val level = batteryIntent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
  val scale = batteryIntent?.getIntExtra(BatteryManager.EXTRA_SCALE, -1)

  return if (level != null && scale != null) {
    level.toInt() / scale.toInt()
  } else {
    -1
  }
}

Location of ios and android code:

image.png

Example code modification: image.pngrun the program:

image.pngSee print -1, because it is the reason of the simulator.

2. Plugin upload

The configuration of pubspec.yaml image.pngsee command

//验证
flutter packages pub publish --dry-run

image.png

flutter packages pub publish --server=[https://pub.dartlang.org](https://pub.dartlang.org/)

View upload results:image.png

Guess you like

Origin juejin.im/post/7258526520166924325