With Google’s backing and cross-platform features, Flutter has an increasingly diverse ecosystem. Currently, most of the apps that can be used by Flutter can be found on pub.flutter- IO. This article introduces the most common plugin for Flutter to avoid repetitive wheel building and for the novice to avoid detours.

DIO Network request framework

When it comes to the web framework of Flutter, DIO has to be mentioned, and DIO is proudly developed by Chinese people. As a network framework, DIO implements all network requests, including GET, POST, PUT, PATCH, DELETE, etc. It also supports interceptors, error capture and file download. With DIO, data interaction between the Flutter App and the backend can be quickly completed. Example 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());
Copy the code

The latest version of DIO is 4.0, there are nearly 10,000 stars on Github, the popularity index reaches 99%, the project address is: pub.flutter-io.cn/packages/di…

Url_launcher System application redirects

When you’re in an App and you’re inevitably going to use a URL to jump to the system browser or some other application, the URl_launcher comes in handy. It’s easy to use:

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';
Copy the code

Url_launcher allows you to jump to the browser of the system, open a web page, and jump to the interface for making calls and sending SMS messages. The popularity is 100% on pub, and the project address is pub.flutter-io.cn/packages/ur…

Flutter_easyrefresh Pull up refresh

Flutter is the best choice for pull-up loading data. It was also developed in The US and supports pull-up loading or pull-down refreshing on most components. It’s easy to use, and supports custom headers and footers.

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

The popularity of Flutter_easyrefresh on pub is 95%. The project address is: pub.flutter-io.cn/packages/fl…

Flutter_swiper Multicast component

Flutter_swiper is a spin component that claims to be the best spin component for FLUTTER. Flutter_swiper supports automatic rotation, display page instructions, animation duration, click callback and other parameters.

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.)Copy the code

Flutter_swiper is 99% popular. The project address is pub.flutter-io.cn/packages/fl…

Catcher exception capture

Catcher is a global exception capture plug-in for FLUTTER, which can automatically catch system exceptions and automatically report runtime errors to the server by specifying the exception reporting address, so as to facilitate developers to track application bugs and fix 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(["[email protected]"]]);/// STEP 2. Pass your root widget (MyApp) along with Catcher configuration:
  Catcher(rootWidget: MyApp(), debugConfig: debugOptions, releaseConfig: releaseOptions);
}
Copy the code

Catcher has a 95% popularity rating and is available at pub.flutter-io.cn/packages/ca…

Cached_network_image Network image loading cache

Cached_network_image is similar to iOS’s SDWebImage in that it caches images that have already been loaded without repeated downloads, increasing load times and saving network resource requests. Cached_network_image also supports placeholder maps, load progress, and placeholder components for failed requests, making it a great user experience.

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

Cached_network_image has a 99% popularity and the project address is pub.flutter-io.cn/packages/ca…

Shared_preferences Local offline key-value pair cache

Shared_preferences Similar to NSUserDefaults of iOS and SharedPreferences of Android, it supports simple key-value offline caching of apps and is suitable for storing simple data offline. However, it should be noted that the plug-in’s offline write operation is asynchronous, so it cannot guarantee 100% success of the write return. Therefore, it is not recommended for 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);
}
Copy the code

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

Image_picker and multi_image_pikcer image pickers

Image_picker and multi_image_picker are image pickers. The former supports single image selection and the latter supports multiple image selection. Both of them support camera or album selection. Note that the multi_image_picker default language is English, you need to configure the 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), ), ); }}Copy the code

The image_picker project address is: pub.flutter-io.cn/packages/im… The multi_image_picker project address is pub.flutter-io.cn/packages/mu… .

Marquee Scroll text component

Marquee can be used when the text is too long to wrap or truncate, and marquee scrolls automatically when the text exceeds the width of the container. Marquee also supports setting various parameters of text, such as font, scroll direction, white 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,
)
Copy the code

Marquee is 96% popular and the project address is: pub.flutter-io.cn/packages/ma… .

Sqflite local database access

Sqflite is a tool for mobile phone sqLite database access. It supports all add, delete and check operations of SQLite database, as well as 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();
Copy the code

Sqflite has a popularity of 100%, and it is best to encapsulate another layer for better maintenance in the application. The project address is: pub.flutter-io.cn/packages/sq… .