Study harmoniously! Don’t be impatient!! I’m your old friend, Xiao Qinglong

preface

  • How to model Flutter using third-party libraries HTTP and JSON

Earlier, we mentioned that Flutter’s common “web request libraries” include HTTP and DIO.

The use of HTTP has also been given in the link article at the beginning, this article will explain the following content:

  • The use of dio

  • "Network Request Encapsulation" for DIO Library

The use of dio

1. Open theThird Party Open Source library

2, search,dio

3. Copy the version number

4, open thepubspec.yamlconfigure

5. Click the button to load the third-party library

6. Go to the place where you need to initiate the request

import 'package:dio/dio.dart';

void main() {
  getHttp();
}

void getHttp() async {
  try {
    var response = await Dio()
        .get('http://rap2api.taobao.org/app/mock/293606/api/chat/list');
    print('Print result:$response');
  } catch (e) {
    print('Exception information:$e'); }}Copy the code

7. Running results

Encapsulate the network request “Dio” library

Create a request management class – SSJRequestManager

Create a DART file: ssj_request_Manager.dart

As follows:

import 'package:dio/dio.dart';

// Enumeration type - Request type
enum HttpType { HttpTypeGet, HttpTypePost }

class SSJRequestManager {
  // singleton method
  static Dio? _dioInstance;
  static Dio getSSJRequestManager() {
    if (_dioInstance == null) {
      _dioInstance = Dio();
    }
    return_dioInstance! ; }// Throw method - get request
  static Future<Response> get(String requestUrl) async {
    return await _sendHttpRequest(HttpType.HttpTypeGet, requestUrl);
  }

  // Throw a method-post request
  static Future<Response> post(String requestUrl,
      {Map<String.dynamic>? queryParameters}) async {
    return await _sendHttpRequest(HttpType.HttpTypePost, requestUrl,
        queryParameters: queryParameters);
  }

  // Private methods - Handle GET requests, POST requests
  static Future _sendHttpRequest(HttpType type, String requestUrl,
      {Map<String.dynamic>? queryParameters, dynamic data}) async {
    try {
      switch (type) {
        case HttpType.HttpTypeGet:
          return await getSSJRequestManager().get(requestUrl);
        case HttpType.HttpTypePost:
          return await await getSSJRequestManager()
              .post(requestUrl, queryParameters: queryParameters, data: data);
        default:
          throw Exception('Error: requests only support GET and POST'); }}on DioError catch (e) {
      print("Error:$e"); }}// Throw method - download file
  static void downloadFile(String downLoadUrl, String savePath,
      void Function(bool result) func) async {
    DateTime timeStart = DateTime.now();
    print('Start download ~ Current time:$timeStart');
    try {
      Dio dio = getSSJRequestManager();
      var response = await dio.download(downLoadUrl, savePath,
          onReceiveProgress: (int count, int total) {
        String progressValue = (count / total * 100).toStringAsFixed(1);
        print('Current download progress:$progressValue% ');
      }).whenComplete(() {
        DateTime timeEnd = DateTime.now();
        // How many seconds
        int second_use = timeEnd.difference(timeStart).inSeconds;
        print('File download time$second_useSeconds');
        func(true);
      });
    } catch (e) {
      print("DownloadFile error:$e"); }}}Copy the code

Case study – Download files

Download files – to Mac desktop
import 'package:flutter_async_programming/tools/ssj_request_manager.dart';

void main() {
  String savePath = "/ Users/JSS/Desktop/downloadFiles/WeChat. DMG." ";
  String downLoadUrl =
      "https://edu-files-1251502357.cos.ap-shanghai.myqcloud.com/CourseTeacher_2.8.1.13_DailyBuild.dmg";

  SSJRequestManager.downloadFile(downLoadUrl, savePath, (result) {
    if (result) {
      print("Download successful");
    } else {
      print("Download failed"); }}); }Copy the code

Running effect

Download the file – to the real iPhone

You need to load a tripartite library: path_provider

The path_provider plug-in is used to retrieve various directories.

The specific code is as follows

import 'package:flutter/material.dart';
import 'package:flutter_async_programming/tools/ssj_request_manager.dart';
import 'package:path_provider/path_provider.dart';

void main() {
  downLoadMethod();
}

/// download
void downLoadMethod() {
  _localFile.then((savePath) {
    print('Download path:$savePath');

    String downLoadUrl =
        "https://edu-files-1251502357.cos.ap-shanghai.myqcloud.com/CourseTeacher_2.8.1.13_DailyBuild.dmg";

    SSJRequestManager.downloadFile(downLoadUrl, savePath, (result) {
      if (result) {
        print("Download successful");
      } else {
        print("Download failed"); }}); }); }/// Get the sandbox folder directory
Future<String> get _localPath async {
  WidgetsFlutterBinding.ensureInitialized(); // Resolve json loading error
  final directory = await getApplicationDocumentsDirectory();
  return directory.path;
}

/// Concatenate the specific file path
Future<String> get _localFile async {
  final path = await _localPath;
  // return File('$path/counter.txt');
  // return File('$path/downloadFiles/ weising.dmg ');
  return '$path/ downloadFiles/WeChat. DMG ';
}
Copy the code

Operation effect:

Then download the app file directory on your phone to the local, and right-click to display the package content

And then we found the file we just downloaded, wech.dmg

Note This function is available on iOS real phones.

Android real machine test environment, currently there is no, so this requires partners to test themselves.

Case – GET request

import 'package:flutter_async_programming/tools/ssj_request_manager.dart';

void main() {
  / / get request
  String urlString = "http://rap2api.taobao.org/app/mock/293606/api/chat/list";
  SSJRequestManager.get(urlString).then((value) {
    print('\n\n2222 request return:$value');
  });
}
Copy the code

Running effect

Post request, because there is no related test conditions, here will not test, friends can test themselves.

supplement

There is no complete package library, because DIO has so many extension methods that there is no need to expose all of them to the outside world. So it’s at your discretion.

Path_provider introduction

Reference article: blog.csdn.net/m0_52390420…

The path_provider plug-in is used to retrieve various directories.

Other methods:

  • GetTemporaryDirectory () : Get temporary file path (IOS and Android only)

  • For getApplicationSupportDirectory () application support directory (IOS and android gm)

  • For getApplicationDocumentsDirectory () application file directory (IOS and Android), in view of the Android devices AppDate directory, IOS devices NSDocumentDirectory directory

  • GetLibraryDirectory () : Get the persistent directory path of the app (IOS only)

  • External.getexternalstoragedirectory () : access to memory card catalog (android available only)

  • For getExternalCacheDirectories () external cache directory (android available only)

  • GetDownloadsDirectory () : Get the download directory (desktop only)