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

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