articles_controller.dart 1.4 KB
Newer Older
yenisleydi committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
import 'dart:convert';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:primer_practica/src/models/articles_model.dart';

import '../http_api/articles_api.dart';

class ArticleController {
  final Connectivity _connectivity = Connectivity();
  final ArticlesApi _articleApi = ArticlesApi();

  Future<Map<String, dynamic>> getArticles(int categoryId) async {
    Map<String, dynamic> mapResp = {
      'ok': false,
      'message': 'No hay artículos',
      'data': null
    };

    ConnectivityResult connectivityResult = await _connectivity.checkConnectivity();
    if (connectivityResult != ConnectivityResult.none) {
      if (connectivityResult == ConnectivityResult.wifi || connectivityResult == ConnectivityResult.mobile) {
        Map<String, dynamic> respGet = await _articleApi.getArticles();

        if (respGet['statusCode'] == 200) {
          try {
            var decodeResp = json.decode(respGet['body']);
            List<ArticlesModel> listArticles = ArticlesModel.fromJsonArray(decodeResp['data']);
            mapResp['ok'] = true;
            mapResp['message'] = "${listArticles.length} artículos encontrados";
            mapResp['data'] = listArticles;
          } catch (e) {
            mapResp['message'] = "Error en el procesamiento de datos: $e";
          }
        } else {
          mapResp['message'] = "${respGet['body']}";
        }
      }
    }

    return mapResp;
  }
}