This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

wedge

There is a purely fictional story that xiao Wang was very cautious before he became Lao Wang. For example, he has a girlfriend, and he wants people to know he has a girlfriend, but he doesn’t want people to know who she is. Paradoxical, isn’t it? This is why Wang is so careful that if he changes his girlfriend one day (maybe he changes her very hard), he will not be laughed at or called a “cheating man”.

What to do? After all, xiao Wang is a person who has studied history. He remembered the story of liu Che, emperor Wudi of the Han Dynasty, when he was young, and repeated this history.

Xiao Wang’s girlfriend

Xiao Wang’s girlfriend is young and beautiful, and her English name is “Dio”. It is said that she is a social butterfly in the pub, and everyone basically relies on her to keep in touch with each other. Wang is very low-key and does not want anyone to know that her girlfriend is Dio, so she only says that she has a girlfriend and that she is named HttpUtil. At the moment, HttpUtil is just Dio in a coat, but when Wang changes to another girlfriend, no one can tell because it’s just HttpUtil from the outside. Xiao Wang secretly called it “The golden House of Dio.”

Xiao Wang used HttpUtil to show Dio’s communication skills, such as Get, Put, Post, Patch, Delete and Upload. This gives Wang a lot of face, because everyone thinks he has a good girlfriend, even though they haven’t met. Many years later, when Xiao Wang became the empress of Lao Wang, Lao Wang’s son hired a group of programmers. Only then did he realize that programmers had invented this technique long ago and came up with a special term for it, called encapsulation.

HttpUtil

In the beginning, Xiao Wang’s HttpUtil looked like this. But it’s too much trouble to find out that every communication skill of introducing a girlfriend has to be talked about how to deal with awkward situations in the process of communication.

class HttpUtil {
  static Dio _dioInstance;
  static Dio getDioInstance() {
    if (_dioInstance == null) {
      _dioInstance = Dio();
    }

    return _dioInstance;
  }

  static Future get(String url, {Map<String.dynamic> queryParams}) async {
    try{
      return await HttpUtil.getDioInstance().get(url, queryParameters: queryParams);
    } on DioError catch (e) {
      EasyLoading.showError(e.message);
    } on Exception catch(e) { EasyLoading.showError(e.toString()); }}/ /...
}
Copy the code

Xiao Wang saved the trouble and made an improvement by presenting all the skills together in another way. When presenting all the skills in this way, it only needs to introduce how to deal with the awkward situation once, after all, the embarrassing situation is the same. First, Wang defines the ability of a girlfriend like a book.

enum HttpMethod {
  GET,
  PUT,
  POST,
  PATCH,
  DELETE,
  UPLOAD,
}
Copy the code

Then he defined the words he used to introduce his girlfriend:

static Future sendRequest(HttpMethod method, String url,
      {Map<String.dynamic> queryParams, dynamic data}) async {
  try {
    switch (method) {
      case HttpMethod.GET:
        return await HttpUtil.getDioInstance()
            .get(url, queryParameters: queryParams);
      case HttpMethod.PUT:
        return await HttpUtil.getDioInstance()
            .put(url, queryParameters: queryParams, data: data);
      case HttpMethod.POST:
        return await HttpUtil.getDioInstance()
            .post(url, queryParameters: queryParams, data: data);
      case HttpMethod.PATCH:
        return await HttpUtil.getDioInstance()
            .patch(url, queryParameters: queryParams, data: data);
      case HttpMethod.DELETE:
        return await HttpUtil.getDioInstance()
            .delete(url, queryParameters: queryParams, data: data);
      default:
        EasyLoading.showError('Request mode error'); }}on DioError catch (e) {
    EasyLoading.showError(e.message);
  } on Exception catch (e) {
    EasyLoading.showError(e.toString());
  }

  return null;
}
Copy the code

At this point, it is much easier to introduce a specific ability.

static Future get(String url, {Map<String.dynamic> queryParams}) async {
    return await sendRequest(HttpMethod.GET, url, queryParams: queryParams);
  }

static Future put(String url,
    {Map<String.dynamic> queryParams, dynamic data}) async {
  return await sendRequest(HttpMethod.PUT, url,
      queryParams: queryParams, data: data);
}

static Future post(String url,
    {Map<String.dynamic> queryParams, dynamic data}) async {
  return await sendRequest(HttpMethod.POST, url,
      queryParams: queryParams, data: data);
}

static Future patch(String url,
    {Map<String.dynamic> queryParams, dynamic data}) async {
  return await sendRequest(HttpMethod.PATCH, url,
      queryParams: queryParams, data: data);
}

static Future delete(String url,
    {Map<String.dynamic> queryParams, dynamic data}) async {
  return await sendRequest(HttpMethod.DELETE, url,
      queryParams: queryParams, data: data);
}

static Future uploadSingle(String url, String fileKey, File file,
    {Map<String.dynamic> queryParams}) async {
  FormData formData = FormData.fromMap({
    fileKey: await MultipartFile.fromFile(file.path),
  });
  return await sendRequest(HttpMethod.POST, url,
      queryParams: queryParams, data: formData);
}
Copy the code

The outside world

With everything in place, Wang began to cut his girlfriend Dio off from the outside world. From then on, people in the outside world only knew that Wang had a girlfriend named HttpUtil. As for who he was and how he looked, it all depended on Wang’s mouth! DynamicService:

import '.. /utils/http_util.dart';

class DynamicService {
  static String host = 'http://localhost:3900/api/';
  static Future list(page, pageSize) async {
    var result = await HttpUtil.get(
      host + 'dynamics',
      queryParams: {'page': page, 'pageSize': pageSize},
    );

    return result;
  }

  static Future get(String id) async {
    var result = await HttpUtil.get(
      host + 'dynamics/' + id,
    );

    return result;
  }

  static Future post(Map<String.dynamic> data) async {
    var result = await HttpUtil.post(host + 'dynamics', data: data);

    return result;
  }

  static Future updateAll(String id, Map<String.dynamic> data) async {
    var result = await HttpUtil.put(host + 'dynamics/' + id, data: data);

    return result;
  }

  static Future update(String id, Map<String.dynamic> data) async {
    var result = await HttpUtil.patch(host + 'dynamics/' + id, data: data);

    return result;
  }

  static Future updateViewCount(String id) async {
    var result = await HttpUtil.patch(host + 'dynamics/view/' + id);

    return result;
  }

  static Future delete(String id) async {
    var result = await HttpUtil.delete(
      host + 'dynamics/' + id,
    );

    returnresult; }}Copy the code

Another example is DynamicAdd.

/ /...
var response = await DynamicService.post(newFormData);
if(response ! =null && response.statusCode == 200) {
  Dialogs.showInfo(context, 'Add successful');
  GetIt.instance
      .get<DynamicListener>()
      .dynamicAdded(DynamicEntity.fromJson(response.data));
  Navigator.of(context).pop();
} else {
  Dialogs.showInfo(this.context, response? .statusMessage ! =null ? response.statusMessage : 'Failed to add');
}
/ /...
Copy the code

The ending

Wang to the outside of the image is more mysterious, everyone wants to see wang’s capable girlfriend, but every time wang talk is HttpUtil, and he himself is also very satisfied with his “golden house hidden jiao” idea, until one day he became the old king, his son – the new wang to his mess.

— To be continued

Knowledge combing

  • Encapsulation: for third-party plug-ins, we don’t rule out after may change, so the best way is to the third party plug-ins encapsulate, hide specific implementation details, so assuming that we need to replace the plug-in, you just need to the wrapper class, rather than having a third party plug-in scattered in various modules, this change is very painful, and easily missed. For example, if we change the previous network request code, we need to modify one file after another.
  • When calling a network request, using the await will wait for the result to return. Without the await, an asynchronous execution will occur and the result is that the exception catching code does not work. Try stopping the backend service after HttpUtil cancellations the await.

The source code has been uploaded to Dio encapsulation source code