zoukankan      html  css  js  c++  java
  • 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
    '),
            ),
          ),
        );
      }
    }

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

    真机测试通过,日志如下

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

  • 相关阅读:
    [HNOI2007]最小矩形覆盖
    [HAOI2008]下落的圆盘
    JSON相关 JSON在线解析 JSON压缩转义工具 JSON着色工具 JSON 在线格式化工具 在线XML/JSON互相转换工具 XML、JSON在线转换
    速度竟差9倍!6款32GB USB3.0优盘横评
    Linux 中用 dd 命令来测试硬盘读写速度
    CrystalDiskMark v7.0.0h中文版
    个人觉得,不单是教育缺失的问题,贫穷才是真像。贫穷分
    就算是3.0的U盘,写入速度10M及以下也是正常的,U盘用很差的闪存颗粒的话就算10Gbps的USB3.1也是很慢的。
    USB历代标准及接口发展
    测试 USB 存储设备读写性能(Mb/s),平均读写速度等
  • 原文地址:https://www.cnblogs.com/loaderman/p/12061065.html
Copyright © 2011-2022 走看看