Summary of common plug ins for Flutter

  • 2021-12-12 09:49:31
  • OfStack

Directory DIO Network Request Framework url_launcher System Application Jump flutter_easyrefresh pull-up refresh flutter_swiper carousel component catcher Exception Trapping cached_network_image Network Picture Load Cache shared_preferences Local Offline Key-Value Pair Cache image_picker and multi_image_pikcer picture selectors marquee Scroll Text Component sqflite Local Database Access

DIO Network Request Framework

When you mention the network framework of Flutter, you have to mention DIO, and it is proud that DIO was developed by Chinese people! As a network framework, DIO implements all network requests, including GET, POST, PUT, PATCH, DELETE, etc. It also supports interceptor, error capture and file download. With the help of DIO, the data interaction between Flutter App and backend can be completed quickly. The sample code is as follows:


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());

The latest version of DIO is 4.0, and there are nearly 10,000 Star on github, with the popularity index reaching 99%. The project address is pub. flutter-io. cn/packages/di …

url_launcher System Application Jump

In App, it is inevitable to use url to jump to the system browser or other applications. At this time, url_launcher comes in handy, and its usage is 10 points simple:


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 supports jumping to the browser of the system to open web pages, jumping to make phone calls and send short messages, and its popularity is 100% on pub. The project address is pub.flutter-io.cn/packages/ur …

flutter_easyrefresh pull-up refresh

flutter pull-up and pull-down loading data is not 2 choices, but also developed by Chinese people, support the implementation of pull-up loading or pull-down refresh on most components. It is also very simple to use, and it also supports custom header and footer.


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

The popularity of flutter_easyrefresh on pub is 95%, and the project address is pub. flutter-io. cn/packages/fl …

flutter_swiper carousel component

flutter_swiper is a carousel component, which claims to be the best carousel component of flutter. flutter_swiper supports automatic carousel, display page indication, animation duration, click callback and other parameter settings.


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,
)

The popularity of flutter_swiper has reached 99%, and the project address is pub. flutter-io. cn/packages/fl …

catcher Exception Trapping

catcher is a global exception catching plug-in of flutter, which can automatically catch system exceptions, and can specify an exception reporting address to automatically report running errors to the server, so as to facilitate developers to track Bug of programs and repair them.


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);
}

The popularity of catcher has reached 95%, and the project address is pub. flutter-io. cn/packages/ca …

cached_network_image Network Picture Load Cache

cached_network_image is somewhat similar to SDWebImage of iOS, which can cache loaded pictures without repeated downloads, which not only improves loading speed, but also saves network resource requests. At the same time, cached_network_image supports placeholder, load progress and request failure placeholder components, which can achieve a good user experience.


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

The popularity of cached_network_image has reached 99%, and the project address is pub. flutter-io. cn/packages/ca …

shared_preferences Local Offline Key-Value Pair Cache

shared_preferences is similar to NSUserDefaults of iOS and SharedPreferences of Android, and supports offline caching of simple key-value pairs of App, which is suitable for offline storage of simple data. However, it should be noted that the offline write operation of plug-ins is asynchronous, so there is no guarantee that 100% storage will be successful after the write is returned, so it is not recommended for 10-point critical data.


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);
}

The popularity of shared_preferences is 100%, and the project address is pub. flutter-io. cn/packages/sh …

image_picker and multi_image_pikcer picture selectors

image_picker and multi_image_picker are picture selectors. The former supports single picture selection, while the latter supports multi-picture selection. Both of them support camera or photo album selection. It should be noted that the default language of multi_image_picker is English, and you need to configure your own local language.


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),
      ),
    );
  }
}

The project address of image_picker is: pub. flutter-io. cn/packages/im …, and the project address of multi_image_picker is: pub. flutter-io. cn/packages/mu …. In fact, in fact, the

marquee scrolling text component

You can use marquee when the text is too long and you don't want to break or truncate. marquee will automatically scroll after the text exceeds the width of the container. At the same time, marquee supports setting various parameters of text, such as font, scroll direction, blank space, scroll speed and so on.


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,
)

The popularity of marquee has reached 96%, and the project address is pub. flutter-io. cn/packages/ma …. In fact, in fact, the

sqflite Local Database Access

sqflite knows from its name that it is a tool for accessing sqlite database on mobile phone, which supports all the operations of adding, changing, deleting and checking sqlite database, and also supports transaction and batch operations. SQL operations support direct execution of SQL statements, as well as template syntax.


// 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();

The popularity of sqflite has reached 100%. If it is best to package another layer for better maintenance in application, the project address is pub. flutter-io. cn/packages/sq ….

The above is the Flutter commonly used plug-in summary of the details, more about Flutter commonly used plug-in information please pay attention to other related articles on this site!


Related articles: