Untitled

 avatar
unknown
plain_text
2 years ago
1.5 kB
12
Indexable
import 'BaseApiServices.dart';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

import 'app_exception.dart';

class NetworkApiService extends BaseApiServices {
  @override
  Future authApiResponse(String url, dynamic data) async {
    dynamic responseJson;
    var headers = {'Content-Type': 'application/x-www-form-urlencoded'};
    var request = http.Request('POST', Uri.parse(url));
    request.bodyFields = {
      'params': json.encode(data),
    };
    request.headers.addAll(headers);
    try {
      final response = await http
          .put(Uri.parse(url), body: data, headers: headers)
          .timeout(const Duration(seconds: 30));

      responseJson = returnResponse(response);
    } on SocketException {
      //socket Exception is not internet
      throw FetchDataException("No Internet Connection");
    }

    return responseJson;
  }

  dynamic returnResponse(http.Response response) {
    switch (response.statusCode) {
      case 200:
      case 201:
        dynamic responseJson = jsonDecode(response.body);
        return responseJson;
      case 400:
        Map errorMessage = jsonDecode(response.body);
        throw BadRequestException(errorMessage["message"].toString());
      case 500:
      case 404:
        throw UnAuthorisedException(response.body.toString());
      default:
        throw FetchDataException(
            "Error occurred while communicating with server with status code ${response.statusCode}");
    }
  }
}
Editor is loading...