articles_controller.dart 1.43 KB
Newer Older
1 2 3 4 5
import 'dart:convert';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:practica1_flutter/src/models/article_model.dart';

import '../http_api/articles_api.dart';
6
import '../models/article.dart';
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 42

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

  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<ArticleModel> listArticles = ArticleModel.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;
  }
}