新建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/

Flutter Plugin开发简单示例的更多相关文章

  1. Flutter Plugin开发流程

    这篇文章主要介绍了Flutter Plugin开发流程,包括如何利用Android Studio开发以及发布等. 本文主要给大家介绍如何开发Flutter Plugin中Android的部分.有关Fl ...

  2. Android学习笔记—Windows下NDK开发简单示例

    该示例假设Android开发环境已经搭建完成,NDK也配置成功: 1.在Eclipse上新建Android工程,名称为ndkdemo.修改res\layout\activity_main.xml &l ...

  3. thrift服务端到客户端开发简单示例

    (1)首先我们在服务器端写个helloworld.thrift文件,如下所示: service HelloWorld{ string ping(1: string name), string getp ...

  4. 2017.2.20 activiti实战--第二章--搭建Activiti开发环境及简单示例(二)简单示例

    学习资料:<Activiti实战> 第一章 搭建Activiti开发环境及简单示例 2.5 简单流程图及其执行过程 (1)leave.bpmn 后缀名必须是bpmn.安装了activiti ...

  5. [xfire]使用xfire开发webservice的简单示例

    目前项目上有用到xfire,所以临时看了些xfire的资料和示例,自己照着写了一个简单示例. xfire在2007年后已经停止更新,正式更名为apache cxf,也可以说是xfire2.0. xfi ...

  6. Flutter实战:手把手教你写Flutter Plugin

    前言 如果你对移动端有所关注,那么你一定会听说过Flutter.得益于Google,Flutter一经推出便得受到了广泛关注.很多开发者跃跃欲试,国内部分大厂,诸如美团.闲鱼等团队已经开始了Flutt ...

  7. 【Flutter 混合开发】嵌入原生View-Android

    Flutter 混合开发系列 包含如下: 嵌入原生View-Android 嵌入原生View-IOS 与原生通信-MethodChannel 与原生通信-BasicMessageChannel 与原生 ...

  8. 开发简单的Kafka应用

    之前基于集群和单机安装过kafka,现在利用kafka提供的API构建一个简单的生产者消费者的项目示例,来跑通kafka的流程,具体过程如下: 首先使用eclipse for javaee建立一个ma ...

  9. HTML-003-模拟IDE代码展开收起功能简单示例

    当先我们在日常的编程开发工作中使用编程工具(例如 Eclipse.Sublime 等等)都有相应的代码折叠展开功能,如下图所示,极大的方便了我们的编码工作.

随机推荐

  1. warning警告问题解决1

    warning警告问题, 这时可以不去管它, 但如果想解决, 可以这样做: c:\python\lib\site-packages\locust\core.py:17: MonkeyPatchWarn ...

  2. 行业——5G

    1.  概述 1.1  定义 5G:5th Generation Mobile Networks / 5th Generation Wireless Systems,第5代移动通信技术 1.2  商标 ...

  3. vue项目积累

    (1)--save和--save-dev 安装到开发环境npm axios --save-dev 安装到生产环境npm axios --save .

  4. python基础语法1 用户交互,基本数据类型,格式化输出,运算符

    与用户交互: 输入: python2: input一定要声明你输入的类型 >>> input(">>:") >>:sean Traceba ...

  5. 为什么在 Java 中128==128返回false,而127==127返回true呢?

    为什么在 Java 中128==128返回false,而127==127返回true呢? 有这样一段代码 Integer a=127; Integer b=127; System.out.printl ...

  6. 用Python 打开程序的两中方法

    1.ShellExecute函数 import win32api win32api.ShellExecute(0, 'open', 'notepad.exe', '', '', 0) # 后台执行 w ...

  7. 11.06水题Test

    11.06水题比赛 题目 描述 做法 \(BSOJ5150\) 求\(n\)个数两两之差的中位数 二分中位数,双指针判定\(\le x\)差值对数 \(BSOJ5151\) 求树的最大匹配和其个数 来 ...

  8. roughViz 一个可重用,功能强大的手绘图表组件

    前段时间介绍过一个chart.xkcd 的手绘图表组件,roughViz 是另外一个,同时也提供了 比较多的图表类型,api 参考文档也比较全 支持的图表类型 Bar Horizontal Bar D ...

  9. Vuejs模板绑定

    一.Vue实例 ①el:指定被Vue管理的模板入口,网页中的DOM节点,但是不能使用body和html,必须是一个普通的HTML标签节点,一般是div ②data:数据驱动视图的数据,在data中初始 ...

  10. ESA2GJK1DH1K微信小程序篇: 安装Nginx,配置反向代理

    前言 一,为什么需要反向代理 小程序访问的是 443端口,咱需要把443端口的数据传给MQTT 这节为了避免大家配置出错,以下源码已经配置. 如果大家想自己配置,请参考 https://www.cnb ...