This article describes how to elegantly encapsulate a network library, including the following points:

  1. JSON to entity objects
  2. Promise like API encapsulation

JSON to entity objects

First, install the Json2Entity tool

flutter packages pub global activate json2entity
Copy the code

Configure boot options:

vim $HOME/.bash_profile

export FLUTTER_HOME=<path to flutter>
export PATH="$PATH:$FLUTTER_HOME/.pub-cache/bin"
Copy the code

The second step is to automatically generate the Dart entity class using json strings

j2e -j '{"result":1,"msg":"ok"}' -o output/BaseEntity
Copy the code

HTTP encapsulation

Encapsulate common GET and POST requests

import 'dart:async';
import 'dart:convert' as Convert;
import 'package:http/http.dart' as http;

class HttpRequest {
  final baseUrl;

  HttpRequest(this.baseUrl);

  Future<dynamic> get(String uri, {Map<String.String> headers}) async {
    http.Response response = await http.get(baseUrl + uri, headers: headers);
    return _processResponse(uri, response);
  }

  Future<dynamic> post(String uri, dynamic body, {Map<String.String> headers}) async {
    http.Response response = await http.post(baseUrl + uri, body: body, headers: headers);
    return _processResponse(uri, response);
  }

  Future<dynamic> _processResponse(String uri, http.Response response) async {
    try {
      final statusCode = response.statusCode;
      final responseBody = response.body;
      var result = Convert.jsonDecode(responseBody);
      return result;
    } on Exception catch (e) {
      if(response ! =null) {
        return {"status": response.statusCode, "message": e.toString()};
      } else {
        return {"status": - 1."message": "Network exception"}; }}}Copy the code

API package

{status: 0, message: "", data: {}} */
class API {
  static const BASE_URL = 'https://xxx.com';
  static const CUSTOM_HEADER = {"": ""};

  static var _request = HttpRequest(API.BASE_URL);

  static Future<dynamic> _get(String uri, {Map<String.String> headers}) async {
    if (headers == null) {
      headers = Map<String.String> (); } headers.addAll(CUSTOM_HEADER);final response = await _request.get(uri, headers: headers);
    
    final status = response['status'];
    if (status == 0) { // Successful return
      final data = response['data'];
      return data;
    } else { // Return on failure
      throw FailureResponse(status, response['message']); }}// Get the list of xx
  static Future<dynamic> getXXList({int start, int limit}) async {
    final data = await _get('/v1/test? start=$start&limit=$limit');
    final items = data['items'];
    final result = List<Entity>();
    for (var item in items) {
      final bean = Entity.fromJson(item);
      result.add(bean);
    }
    returnresult; }}class FailureResponse {
  final int status;
  final String message;
  FailureResponse(this.status, this.message);

  @override
  String toString() {
    return 'status=$status, message=$message'; }}Copy the code

Access the API in a similar way to Promise

API.getXXList(start: 0, limit: 4).then((data) {
    // Update data
}).catchError((error) {
    print(error);
});
Copy the code

The resources

  • Github.com/laxian/dart…
  • Github.com/kaina404/Fl…