Flutter 常用插件匯總

DIO網絡請求框架

提起 Flutter 的網絡框架,就不得不提 DIO,而且令人自豪的是 DIO 是國人開發的哦!DIO 作為一個網絡框架實現瞭全部的網絡請求,包括 GET、POST、PUT、PATCH、DELETE等,同時還支持攔截器,錯誤捕獲和文件下載。借助 DIO,可以快速完成 Flutter App 與後端的數據交互。示例代碼如下:

Response response;
var dio = Dio();
response = await dio.get('/test?id=12&name=wendu');
print(response.data.toString());
// Optionally the request above could also be done as
response = await dio.get('/test', queryParameters: {'id': 12, 'name': 'wendu'});
print(response.data.toString());

DIO最新版本為4.0,在github 上有近萬個 Star,流行指數達到瞭99%,項目地址為:pub.flutter-io.cn/packages/di…​

url_launcher系統應用跳轉

在 App 中不可避免會使用url 跳轉到系統瀏覽器或其他應用,這時候 url_launcher 就派上用場瞭, 用法十分簡單:

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

const _url = 'https://flutter.cn';

void main() => runApp(
      const MaterialApp(
        home: Material(
          child: Center(
            child: RaisedButton(
              onPressed: _launchURL,
              child: Text('Show Flutter homepage'),
            ),
          ),
        ),
      ),
    );

void _launchURL() async =>
    await canLaunch(_url) ? await launch(_url) : throw 'Could not launch $_url';

url_launcher支持跳轉到系統的瀏覽器打開網頁,跳轉撥打電話和發送短信界面,在 pub 上流行度為100%,項目地址為:pub.flutter-io.cn/packages/ur…​

flutter_easyrefresh上下拉刷新

flutter 中上下拉加載數據的不二之選,也是國人開發的,支持在大部分組件上套用實現上拉加載或下拉刷新。使用方法也是很簡單,同時也支持自定義 header 和 footer。

import 'package:flutter_easyrefresh/easy_refresh.dart';
//...
  EasyRefresh(
    child: ScrollView(),
    onRefresh: () async{
      ....
    },
    onLoad: () async {
      ....
    },
  )

flutter_easyrefresh 在 pub 上的流行度為95%,項目地址為:pub.flutter-io.cn/packages/fl…​

flutter_swiper 輪播組件

flutter_swiper 是一個輪播組件,號稱是 flutter 最佳的輪播組件。flutter_swiper 支持自動輪播,顯示頁面指示,動畫時長,點擊回調等多種參數設置。

new Swiper(
  itemBuilder: (BuildContext context, int index) {
    return new Image.network(
      "http://via.placeholder.com/288x188",
      fit: BoxFit.fill,
    );
  },
  itemCount: 10,
  viewportFraction: 0.8,
  scale: 0.9,
)

flutter_swiper 的流行度達到瞭99%,項目地址為:pub.flutter-io.cn/packages/fl…​

catcher 異常捕獲

catcher 是一個 flutter 的全局異常捕獲插件,可以自動捕捉到系統的異常,並且可以指定異常上報地址自動將運行錯誤上報給服務端,從而方便開發者跟蹤程序的 Bug 進而進行修復。

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

main() {
  /// STEP 1. Create catcher configuration. 
  /// Debug configuration with dialog report mode and console handler. It will show dialog and once user accepts it, error will be shown   /// in console.
  CatcherOptions debugOptions =
      CatcherOptions(DialogReportMode(), [ConsoleHandler()]);
      
  /// Release configuration. Same as above, but once user accepts dialog, user will be prompted to send email with crash to support.
  CatcherOptions releaseOptions = CatcherOptions(DialogReportMode(), [
    EmailManualHandler(["[email protected]"])
  ]);

  /// STEP 2. Pass your root widget (MyApp) along with Catcher configuration:
  Catcher(rootWidget: MyApp(), debugConfig: debugOptions, releaseConfig: releaseOptions);
}

catcher 的流行度達到瞭95%,項目地址為:pub.flutter-io.cn/packages/ca…​

cached_network_image 網絡圖片加載緩存

cached_network_image 有點類似iOS的 SDWebImage,可以緩存已經加載過的圖片而無需重復下載,既提高瞭加載速度也節省瞭網絡資源請求。同時 cached_network_image 支持占位圖、加載進度和請求失敗的占位組件,可以做到很好的用戶體驗。

CachedNetworkImage(
        imageUrl: "http://via.placeholder.com/350x150",
        placeholder: (context, url) => CircularProgressIndicator(),
        errorWidget: (context, url, error) => Icon(Icons.error),
     ),
//......

cached_network_image 流行度達到瞭99%,項目地址為:pub.flutter-io.cn/packages/ca…​

shared_preferences 本地離線鍵值對緩存

shared_preferences類似iOS的 NSUserDefaults和安卓的 SharedPreferences,支持App簡單的鍵值對離線緩存,對於離線存儲簡單的數據十分適用。但是需要註意的是插件的離線寫入操作是異步的,因此並不能保證寫入返回後100%存儲成功,因此對於十分關鍵的數據不建議使用。

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

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
      child: RaisedButton(
        onPressed: _incrementCounter,
        child: Text('Increment Counter'),
        ),
      ),
    ),
  ));
}

_incrementCounter() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  int counter = (prefs.getInt('counter') ?? 0) + 1;
  print('Pressed $counter times.');
  await prefs.setInt('counter', counter);
}

shared_preferences的流行度為100%,項目地址為:pub.flutter-io.cn/packages/sh…​

image_picker 和 multi_image_pikcer 圖片選擇器

image_picker 和 multi_image_picker 為圖片選擇器,前者支持單張圖片選擇,後者支持多圖選擇,二者均支持相機或從相冊選擇圖片。需要註意的是 multi_image_picker 默認語言是英文的,需要自己配置本地語言。

import 'dart:io';

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

//......

class _MyHomePageState extends State<MyHomePage> {
  File _image;
  final picker = ImagePicker();

  Future getImage() async {
    final pickedFile = await picker.getImage(source: ImageSource.camera);

    setState(() {
      if (pickedFile != null) {
        _image = File(pickedFile.path);
      } else {
        print('No image selected.');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Picker Example'),
      ),
      body: Center(
        child: _image == null
            ? Text('No image selected.')
            : Image.file(_image),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: getImage,
        tooltip: 'Pick Image',
        child: Icon(Icons.add_a_photo),
      ),
    );
  }
}

image_picker 項目地址為:pub.flutter-io.cn/packages/im…,multi_image_picker 項目地址為:pub.flutter-io.cn/packages/mu…。​

marquee滾動文字組件

遇到文字太長不想換行也不想截斷的時候就可以使用 marquee 瞭,marquee 在文字超出容器寬度後會自動滾動播報。同時,marquee 支持設置文字的多種參數,如字體,滾動方向,留白,滾動速度等等。

Marquee(
  text: 'Some sample text that takes some space.',
  style: TextStyle(fontWeight: FontWeight.bold),
  scrollAxis: Axis.horizontal,
  crossAxisAlignment: CrossAxisAlignment.start,
  blankSpace: 20.0,
  velocity: 100.0,
  pauseAfterRound: Duration(seconds: 1),
  startPadding: 10.0,
  accelerationDuration: Duration(seconds: 1),
  accelerationCurve: Curves.linear,
  decelerationDuration: Duration(milliseconds: 500),
  decelerationCurve: Curves.easeOut,
)

marquee 的流行度達到瞭96%,項目地址為:pub.flutter-io.cn/packages/ma…。​

sqflite 本地數據庫訪問

sqflite 從名字就知道它是用於手機端 sqlite 數據庫訪問的工具,支持 sqlite 數據庫的全部增改刪查操作,同時還支持事務和批量操作。SQL 的操作支持直接執行SQL 語句,也支持模板語法。

// Get a location using getDatabasesPath
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');

// Delete the database
await deleteDatabase(path);

// open the database
Database database = await openDatabase(path, version: 1,
    onCreate: (Database db, int version) async {
  // When creating the db, create the table
  await db.execute(
      'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});

// Insert some records in a transaction
await database.transaction((txn) async {
  int id1 = await txn.rawInsert(
      'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
  print('inserted1: $id1');
  int id2 = await txn.rawInsert(
      'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
      ['another name', 12345678, 3.1416]);
  print('inserted2: $id2');
});

// Update some record
int count = await database.rawUpdate(
    'UPDATE Test SET name = ?, value = ? WHERE name = ?',
    ['updated name', '9876', 'some name']);
print('updated: $count');

// Get the records
List<Map> list = await database.rawQuery('SELECT * FROM Test');
List<Map> expectedList = [
  {'name': 'updated name', 'id': 1, 'value': 9876, 'num': 456.789},
  {'name': 'another name', 'id': 2, 'value': 12345678, 'num': 3.1416}
];
print(list);
print(expectedList);
assert(const DeepCollectionEquality().equals(list, expectedList));

// Count the records
count = Sqflite
    .firstIntValue(await database.rawQuery('SELECT COUNT(*) FROM Test'));
assert(count == 2);

// Delete a record
count = await database
    .rawDelete('DELETE FROM Test WHERE name = ?', ['another name']);
assert(count == 1);

// Close the database
await database.close();

sqflite 流行度達到瞭100%,如果為瞭應用中更好地維護最好是再封裝一層,項目地址為:pub.flutter-io.cn/packages/sq…。

以上就是Flutter 常用插件匯總的詳細內容,更多關於Flutter 常用插件的資料請關註WalkonNet其它相關文章!

推薦閱讀: