Flutter Plugin开发简单示例

新建Plugin项目:

flutter create --template=plugin -i swift -a javahello
  • lib/hello.dart:
    • 插件包的Dart API.
  • android/src/main/java/com/yourcompany/​hello/HelloPlugin.java:
    • 插件包API的Android实现.
  • ios/Classes/HelloPlugin.m:
    • 插件包API的ios实现.
  • example/:
    • 一个依赖于该插件的Flutter应用程序,来说明如何使用它

用AS打开:

编写Android 插件包:

package com.example.hello;

import android.app.Service;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Vibrator;

import java.util.HashMap;
import java.util.Map;


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;
import io.flutter.plugin.common.PluginRegistry.Registrar;

/** HelloPlugin */
public class HelloPlugin implements MethodCallHandler {
  static Context applicationContext;
  /** Plugin registration. */
  public static void registerWith(Registrar registrar) {
    applicationContext=registrar.context();
    final MethodChannel channel = new MethodChannel(registrar.messenger(), "hello");
    channel.setMethodCallHandler(new HelloPlugin());


  }

  @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("PackageInfo")){

      try {  
        //获取APP相关信息
        PackageManager pm = applicationContext.getPackageManager();
        PackageInfo info = pm.getPackageInfo(applicationContext.getPackageName(), 0);
        Map<String, String> map = new HashMap<>();
        map.put("appName", info.applicationInfo.loadLabel(pm).toString());
        map.put("packageName", applicationContext.getPackageName());
        map.put("version", info.versionName);

        map.put("buildNumber", info.versionCode+"");

        result.success(map);

      } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        result.error("Name not found", e.getMessage(), null);
      }


    } else if (call.method.equals("Vibrate")){
      // 震动
      Vibrator vib = (Vibrator) applicationContext.getSystemService(Service.VIBRATOR_SERVICE);
      vib.vibrate(500);
      result.success(null);
    } else {
      result.notImplemented();
    }
  }

}

编写hello.dart

import 'dart:async';

import 'package:flutter/services.dart';

class Hello {
  static const MethodChannel _channel = const MethodChannel('hello');

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

  static Future<PackageInfo> get packageInfo async {
    final Map<dynamic, dynamic> map = await _channel.invokeMethod('PackageInfo');

    PackageInfo _packageInfo = PackageInfo(
      map["appName"],
      map["packageName"],
      map["version"],
      map["buildNumber"],
    );
    return _packageInfo;
  }
  static void get vibrate  {
     _channel.invokeMethod('Vibrate');
  }
}

class PackageInfo {
  String appName;
  String packageName;
  String version;
  String buildNumber;

  PackageInfo(this.appName, this.packageName, this.version, this.buildNumber);
}

在example下使用:

pubspec.yaml引入:

name: hello_example
description: Demonstrates how to use the hello plugin.
publish_to: 'none'

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter



dev_dependencies:
  flutter_test:
    sdk: flutter

  hello:
    path: ../

main.dart调用:

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

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platformVersion = await Hello.platformVersion;
      PackageInfo packageInfo = await Hello.packageInfo;
      print(packageInfo.appName);
      print(packageInfo.packageName);
      print(packageInfo.version);
      print(packageInfo.buildNumber);
      Hello.vibrate;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Text('Running on: $_platformVersion\n'),
        ),
      ),
    );
  }
}

一个简单的插件就开发完毕了,只支持Android,IOS平台先略过哈,后期可以发布pub就可以供其他人使用了!

真机测试通过,日志如下

 

参考文档:https://flutterchina.club/developing-packages/

posted on 2019-12-20 14:44  LoaderMan  阅读(2412)  评论(0编辑  收藏  举报

导航