ArticleApi.dart 1.68 KB
Newer Older
1 2 3 4
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/foundation.dart';
import 'package:miapp_flutter/environments/archivo.dart';
nayeli92433 committed
5
import '../models/ArticuloModel.dart';
6 7

class ArticleApi {
nayeli92433 committed
8
  final String apiUrl = '${apiApp}/articulo'; 
9 10

  Future<Map<String, dynamic>> getArticles(int categoryId) async {
nayeli92433 committed
11
    String url = '$apiUrl?categoria=$categoryId&offset=0&max=100';
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
    if (kDebugMode) {
      print('Url -> $url');
    }
    try {
      final response = await http.get(Uri.parse(url));

      if (response.statusCode == 200) {
        return {
          'statusCode': response.statusCode,
          'body': response.body,
        };
      } else {
        return {
          'statusCode': response.statusCode,
          'body': 'Error: ${response.reasonPhrase}',
        };
      }
    } catch (e) {
      return {
        'statusCode': 501,
        'body': 'Error: $e',
      };
    }
  }
nayeli92433 committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

  Future<List<ArticleModel>> searchArticles(String query) async {
    try {
      final response = await http.get(Uri.parse('$apiUrl?nombre=$query'));
      print('Response status: ${response.statusCode}');
      print('Response body: ${response.body}');

      if (response.statusCode == 200) {
        try {
          final Map<String, dynamic> data = json.decode(response.body);
          final List<dynamic> articlesJson = data['data'];
          return ArticleModel.fromJsonArray(articlesJson);
        } catch (e) {
          throw Exception('Error en procesamiento de datos: $e');
        }
      } else {
        throw Exception('Error en la respuesta de la API: ${response.body}');
      }
    } catch (e) {
      throw Exception('Error en la solicitud a la API: $e');
    }
  }
58
}