Dio Example Usage

03-06-2020
class ApiHelper {
  static const String BASE_PATH = "http://api.example.com";
  static const String API_PATH = "/api";

  Future<ApiResponseModel> request(String url,
      {Map<String, String> queryParameters, bearerToken = ''}) async {
    return _innerRequest(url, 'GET',bearerToken);
  }
  Future<ApiResponseModel> _innerRequest(String url, String type,
      [postParams,bearerToken = '']) async {
    url = _getUrl(url);
    Dio dio = _getDio(bearerToken);
    try {
      var response;
      if(type=='GET')
        response = await dio.get(url);
      else if(type=='POST'){
        log('POST Params: '+postParams);
        response = await dio.post(url, data: postParams);
      }

      else throw Exception('type must be one of GET, POST');
      if (response.statusCode == 200) {
        return _getApiResponseModel(response.data);
      }
    } on DioError catch (e) {
      if(e.response==null) {
        log('Dio Error: '+e.error.message);
        return _getApiUnhandledError();
      }
      if (e.response.statusCode == 400 || e.response.statusCode == 401) {
        return _getApiResponseModel(e.response.data);
      } else {
        return _getApiUnhandledError();
      }
    } catch (error) {
      return _getApiUnhandledError();
    }
  }
  String _getUrl(String url) {
    if (!url.startsWith("/")) url = '/' + url;
    var uri = url.startsWith("https://")
        ? Uri.https(BASE_PATH.substring("https://".length), API_PATH + url)
        : Uri.http(BASE_PATH.substring("http://".length), API_PATH + url);
    log('URL: $uri');

    return uri.toString();
  }

  Dio _getDio(bearerToken) {
    // or new Dio with a BaseOptions instance.
    BaseOptions options = new BaseOptions();
    options.headers["Content-Type"] = "application/json; charset:utf-8";
    options.headers["Accept"] = "application/json";
    if (bearerToken != null && bearerToken != '')
      options.headers["Authorization"] = 'Bearer ' + bearerToken;

    Dio dio = new Dio(options);

    return dio;
  }

  ApiResponseModel _getApiResponseModel(result) {
    var apiResponse = new ApiResponseModel();
    apiResponse.message = result['message'] == 'Unauthenticated.'
        ? 'Oturumunuz kapandı. Lütfen çıkış yapıp tekrar giriş yapınız'
        : result['message'];
    apiResponse.status = result['success'] == null ? false : result['success'];
    apiResponse.data = result['data'];
    return apiResponse;
  }

  ApiResponseModel _getApiUnhandledError() {
    var apiResponse = new ApiResponseModel();
    apiResponse.message = 'Beklenmeyen bir hata oluştu';
    apiResponse.status = false;
    apiResponse.data = '';
    return apiResponse;
  }

  Future<ApiResponseModel> postRequest(String url, postParams,
      [bearerToken = '']) async {
    return _innerRequest(url, 'POST',postParams,bearerToken);
  }

  Future<ApiResponseModel> uploadFile(
      String url, String parameterName, File file,
      [bearerToken = '']) async {
    String fileName = file.path.split('/').last;
    Dio dio = new Dio();

    dio.options.baseUrl = _getUrl(url).toString();
    if (bearerToken != null && bearerToken != '')
      dio.options.headers['Authorization'] = 'Bearer ' + bearerToken;

    FormData formData = FormData.fromMap({
      parameterName:
      await MultipartFile.fromFile(file.path, filename: fileName),
    });
    var response = await dio.post(url, data: formData);
    return _getApiResponseModel(response.toString());
  }
}

© 2019 All rights reserved. Codesenior.COM