首页 > 编程语言 > Flutter 常用插件汇总
2021
07-01

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(["support@email.com"])
  ]);

  /// 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 常用插件的资料请关注自学编程网其它相关文章!

编程技巧