api_response.dart 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import 'dart:convert';
  2. import 'package:http/http.dart';
  3. class ApiResponse {
  4. int? statusCode;
  5. Paginacion? paginacion;
  6. List<Map<String, dynamic>>? resultados;
  7. Map<String, dynamic>? detalle;
  8. Map<String, dynamic>? errores;
  9. String mensaje = '';
  10. bool get isOk => statusCode! >= 200 && statusCode! < 300;
  11. bool get isError => statusCode! >= 400 && statusCode! < 500;
  12. bool get isServerError => statusCode! >= 500;
  13. ApiResponse(Response response) {
  14. statusCode = response.statusCode;
  15. var body = json.decode(response.body);
  16. if (body.containsKey('paginacion')) {
  17. var pag = body['paginacion'];
  18. paginacion = Paginacion(
  19. total: pag['total'],
  20. pagina: pag['pagina'],
  21. limite: pag['limite'],
  22. );
  23. }
  24. if (body.containsKey('mensaje')) {
  25. mensaje = body['mensaje'];
  26. }
  27. if (body.containsKey('resultado') && body["resultado"] != null) {
  28. resultados = (body['resultado'] as List<dynamic>)
  29. .cast<Map<String, dynamic>>()
  30. .toList();
  31. }
  32. if (body.containsKey('detalle')) {
  33. detalle = body['detalle'];
  34. }
  35. if (body.containsKey('errores')) {
  36. errores = body['errores'];
  37. }
  38. }
  39. }
  40. class Paginacion {
  41. final int total;
  42. final int pagina;
  43. final int limite;
  44. Paginacion({required this.total, required this.pagina, required this.limite});
  45. factory Paginacion.fromJson(Map<String, dynamic> json) {
  46. return Paginacion(
  47. total: json['total'],
  48. pagina: json['pagina'],
  49. limite: json['limite'],
  50. );
  51. }
  52. }