Flutter 官方原生接口封装集合

在开发Flutter 应用时候,经常会用到原生的一些api , Flutter 官方对这些常用的 api 进行了封装,以库的形式提供出来,如果有需要可以引入。下面记录的基本是两端通用的。

1. battery(电量)

获取电池电量以及相关状态

pubspec.yaml 添加引入:

dependencies:
	battery: ^0.3.0+5

使用:

import 'package:battery/battery.dart';

// 获取 Battery 实体
var battery = Battery();

// 获取当前 电池电量
print(await battery.batteryLevel);

//监听电池状态变化 : 
// 0 是full , 充满电
// 1 是charging , 充电中
// 2 是discharging , 未充电,拔充电头
battery.onBatteryStateChanged.listen((BatteryState state) {
    print("state: "+state.index.toString());
});

2. connectivity(网络连接情况)

获取网络连接情况

pubspec.yaml 添加引入:

dependencies:
	connectivity: ^0.4.4

使用:

import 'package:connectivity/connectivity.dart';


    // 连接情况  wifi 还是 移动网络
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      print("I am connected to a mobile network.");
    } else if (connectivityResult == ConnectivityResult.wifi) {
      print("I am connected to a wifi network.");
    }

    // 监听网络连接情况的变化
    Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      // Got a new connectivity status!
    });

    //iOS 获取位置信息授权请求,iOS 特有
    Connectivity().requestLocationServiceAuthorization();

    // 获取wifi 相关信息
    var wifiBSSID = await (Connectivity().getWifiBSSID());
    var wifiIP = await (Connectivity().getWifiIP());
    var wifiName = await (Connectivity().getWifiName());

获取wifi 信息,在iOS 端有一定的限制:( 翻译 )

iOS 12:
.getWifiBSSID() 和 .getWifiName() 在 iOS 系统 >=12 时候,XCode 里面 Access WiFi information capability 设置必须是打开状态,不然这两个结果都会是 空。

iOS 13:
.getWifiBSSID() 和.getWifiName() 是利用iOS 里面的 CNCopyCurrentNetworkInfo 方法进行获取的。
iOS 13 系统上,苹果在这个api 上,不再返回有效信息,在iOS 12或者更早的版本会收到一个伪值:

  • SSID: “Wi-Fi” or “WLAN” (“WLAN” will be returned for the China SKU)
  • BSSID: “00:00:00:00:00:00”

在 iOS 13之后,就直接回返回 null 了。

CNCopyCurrentNetworkInfo 在下面的情况会正常工作:

  • 应用使用了 Core Location, 并且用户对使用位置信息进行了授权。
  • 应用使用 NEHotspotConfiguration API 配置当前的 WIFI网络
  • 应用使用了VPN 配置

如果你的应用属于后两类,这个就是能获取到信息的。如果不是属于这两类,你又要获取相关wifi 信息,你就要请求用户获取相关的位置信息授权了。

3.device_info (设备信息)

pubspec.yaml 添加引入:

dependencies:
  device_info: ^0.4.0+2

使用:

import 'package:device_info/device_info.dart';

    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    print('Running on ${androidInfo.model}');

    IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
    print('Running on ${iosInfo.utsname.machine}');

手上一台Android 设备的信息打印了一下,供参考:
在这里插入图片描述
iOS 信息:
在这里插入图片描述

4. image_picker (获取照片或拍摄照片)

Note: This plugin is still under development, and some APIs might not be available yet.
官方提示: 开发中,有些API 还不可用

pubspec.yaml 引入:

dependencies:
  image_picker: ^0.6.1+4

使用:

iOS :
需要在 Info.plist 中,添加相关权限描述,文件位置: /ios/Runner/Info.plist

NSPhotoLibraryUsageDescription
NSCameraUsageDescription
NSMicrophoneUsageDescription

Android:
No configuration required - the plugin should work out of the box.
官方描述是拆箱即用,作为一个Android 开发者有个疑问,权限申请呢?(自动会申请权限,已经封装在里面)

使用示例:

      
      // 相册获取
      var image = await ImagePicker.pickImage(source: ImageSource.gallery);
      setState(() {
        _image = image;
      });
       // 打开相机
       var image2 = await ImagePicker.pickImage(source: ImageSource.camera);
      setState(() {
        _image = image2;
      });

5. package_info(包信息)

pubspec.yaml 引入:

dependencies:
  package_info: ^0.4.0+6

使用:

import 'package:package_info/package_info.dart';

    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    
    // app 名字
    String appName = packageInfo.appName;
    // 包名
    String packageName = packageInfo.packageName;
    // 版本号
    String version = packageInfo.version;
    String buildNumber = packageInfo.buildNumber;

6. path_provider (获取常用文件路径)

pubspec.yaml 引入:

dependencies:
  path_provider: ^1.2.0

使用:

import 'package:package_info/package_info.dart';

    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    
    // app 名字
    String appName = packageInfo.appName;
    // 包名
    String packageName = packageInfo.packageName;
    // 版本号
    String version = packageInfo.version;
    String buildNumber = packageInfo.buildNumber;

7. path_provider (常用文件路径)

pubspec.yaml 引入:

dependencies:
  path_provider: ^1.2.0

使用:

    //获取 Cache 目录
    Directory tempDir = await getTemporaryDirectory();
    print(tempDir.path);

    //获取应用目录
    Directory appDocDir = await getApplicationDocumentsDirectory();
    print(appDocDir.path);

    //o获取外部存储目录,只有 Android 端有效
    Directory externalStorage = await getExternalStorageDirectory();
    print(externalStorage.path);

在这里插入图片描述

8. shared_preferences(App K-V存储功能)

Flutter key-value的数据存储

iOS 端对应的是 : NSUserDefaults
Android 端对应的是: SharedPreferences

pubspec.yaml 引入:

dependencies:
  shared_preferences: ^0.5.3+4

使用

import 'package:shared_preferences/shared_preferences.dart';


    SharedPreferences prefs = await SharedPreferences.getInstance();

    //读取数据
    int counter = (prefs.getInt('counter') ?? 0) + 1;

    print('Pressed $counter times.');

    //写入数据
    await prefs.setInt('counter', counter);

9.url_launcher (启动URL,包括打电话、发短信和浏览网页等功能)

使用:
分别是URL 打开、调起打电话,调起电子邮件、调起短信功能,更多的协议可以参考:
iOS / Android

import 'package:url_launcher/url_launcher.dart';

    // 浏览器打开 url
    const url = 'https://flutter.dev';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }

    // 调起打电话功能
    const url2 = 'tel:+1 555 010 999';
    if (await canLaunch(url2)) {
      await launch(url2);
    } else {
      throw 'Could not launch $url2';
    }

    // 调起电子邮件
    const url3 = 'mailto:[email protected]?subject=News&body=New%20plugin';
    if (await canLaunch(url3)) {
      await launch(url3);
    } else {
      throw 'Could not launch $url3';
    }

    //调起原生短信发送
    const url4 = 'sms:5550101234';
    if (await canLaunch(url4)) {
      await launch(url4);
    } else {
      throw 'Could not launch $url4';
    }

更多

更多Flutter 库,可以参考 : https://pub.dev/flutter/packages

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章