Flutter print any http request automatically – abstract HTTP class

Issue

in short words I want to print in my console any Http request that my app is requesting without putting print command after each call I’m making for example :

let’s say I have service with http.Client.get and I have another 100 service like that.

what I’m doing now is I’m waiting for the response in each service and then I’m printing it like this print('response is ' + response.body);.

what I want to achieve is that will be automatically be printed out for me without me writing print 100 times in after each request I’m making, any good architect would you recommend to follow ?

hope I cleared the idea well.

Solution

well here is my last approach for this.
for every one is seeking for making it with abstraction or let’s say wrapping;
first what I did is kind if wrapping for the HTTP class and used my class everywhere instead of the original Http Class.

so the code would go like this

class MHttpClient {
  final http.Client client;
  final SharedPreferences sharedPreferences;
  MHttpClient(this.client, this.sharedPreferences);

  Future<http.Response> get(
      {String path = "", Map<String, String> extraHeders}) async {
    printWrapped('get Path: $path');
    final response = await client.get(
      Uri.parse(getBaseURL() + Version + path),
      headers: getHeaders(extraHeaders: extraHeders),
    );
    printWrapped("get response : \n" + utf8.decode(response.bodyBytes));
    return response;
  }

  Future<http.Response> post(
      {String body = "",
      String path = "",
      Map<String, String> extraHeders}) async {
    printWrapped('sended body: \n');
    printWrapped(' ${json.decode(body)}');
    final response = await client.post(
      Uri.parse(getBaseURL() + Version + path),
      body: body,
      headers: getHeaders(extraHeaders: extraHeders),
    );
    printWrapped("post response : \n" + utf8.decode(response.bodyBytes));
    return response;
  }

  Future<http.Response> put({String body = "", String path = ""}) async {
    printWrapped('put body: \n ${json.decode(body)}');
    final response = await client.put(
      Uri.parse(getBaseURL() + Version + path),
      body: body,
      headers: getHeaders(),
    );
    printWrapped(utf8.decode(response.bodyBytes));
    return response;
  }

  Future<http.Response> putImage({File image, String path = ""}) async {
    printWrapped('Image Path: $path');
    final response = await http.put(
      Uri.parse(path),
      headers: getImageHeaders(),
      body: image.readAsBytesSync(),
    );
    return response;
  }

  String getBaseURL() {
    if (Foundation.kDebugMode)
      return BaseURLSTAGING;
    else
      return BaseURL;
  }

  String getApiKey() {
    if (Foundation.kDebugMode)
      return ApiKeyStaging;
    else
      return ApiKey;
  }

  String getToken() {
    String cashedToken = sharedPreferences.getString(CACHED_TOKEN);
    if (cashedToken == null) cashedToken = "";
    return cashedToken;
  }

  Map<String, String> getHeaders({Map extraHeaders}) {
    Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      'x-api-key': getApiKey(),
      HttpHeaders.authorizationHeader: 'Bearer ' + getToken(),
    };
    if (extraHeaders == null || extraHeaders.isEmpty)
      return headers;
    else {
      headers.addAll(extraHeaders);
      return headers;
    }
  }

  Map<String, String> getImageHeaders() {
    return <String, String>{'Content-Type': 'image/png'};
  }

  void printWrapped(String text) {
    final pattern = RegExp('.{400}'); // 800 is the size of each chunk
    pattern.allMatches(text).forEach((match) => developer.log(match.group(0)));
  }
}

and then I used MHttpClient else where

final MHttpClient client;
final response = await client.get(path: path);

and in this case I don’t have to warry about anything else ,
and when you need to change one thing you will change it in one place only, and every thing will stay the same and work as you want without braking changes you have to do for all you requested.

Answered By – Baraa Aljabban

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *