From abd13ab88f99bf0ad6f5bf410120cf60075b35c5 Mon Sep 17 00:00:00 2001 From: yenisleydi <126813935+yenisleydi@users.noreply.github.com> Date: Fri, 2 Aug 2024 11:39:59 -0600 Subject: [PATCH] categoria api --- lib/src/controllers/categoty_controller.dart | 58 ++++++++++++++++++++++++++++++++++++++++------------------ lib/src/http_api/category_service.dart | 51 +++++++++++++++++++++++++++++++++++++++++++++++---- lib/src/models/categoryModel.dart | 8 ++++---- lib/src/pages/formulario_categoria.dart | 41 ++++++++++++++++++++++++++++------------- 4 files changed, 119 insertions(+), 39 deletions(-) diff --git a/lib/src/controllers/categoty_controller.dart b/lib/src/controllers/categoty_controller.dart index eb3019b..607057d 100644 --- a/lib/src/controllers/categoty_controller.dart +++ b/lib/src/controllers/categoty_controller.dart @@ -1,46 +1,68 @@ -import 'dart:convert'; // Importa el paquete para trabajar con JSON. +import 'dart:convert'; // Para convertir datos a JSON import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:primer_practica/src/http_api/category_service.dart'; import 'package:primer_practica/src/models/categoryModel.dart'; - class CategoryController { - final Connectivity _connectivity = Connectivity(); // Crea una instancia de Connectivity para verificar el estado de la red. + final Connectivity _connectivity = Connectivity(); + // Método para obtener las categorías Future> getCategories() async { - // Inicializa la respuesta por defecto. Map mapResp = { 'ok': false, 'message': 'No hay categorias', 'data': null }; - // Verifica la conectividad. - ConnectivityResult connectivityResult = (await _connectivity.checkConnectivity()) as ConnectivityResult; + ConnectivityResult connectivityResult = (await _connectivity.checkConnectivity()); - // Si hay conexión a internet. if (connectivityResult != ConnectivityResult.none) { if (connectivityResult == ConnectivityResult.wifi || connectivityResult == ConnectivityResult.mobile) { - CategoryService categoryApi = CategoryService(); // Crea una instancia de CategoryApi. - Map respGet = await categoryApi.getCategories(); // Obtiene las categorías desde la API. + CategoryService categoryApi = CategoryService(); + Map respGet = await categoryApi.getCategories(); - // Si la respuesta de la API es exitosa. if (respGet['statusCode'] == 200) { try { - var decodeResp = json.decode(respGet['body']); // Decodifica la respuesta JSON. - List listCategories = CategoryModel.fromJsonArray(decodeResp['data']); // Convierte los datos en una lista de categorías. - mapResp['ok'] = true; // Marca la operación como exitosa. - mapResp['message'] = "${listCategories.length} categorias encontradas"; // Actualiza el mensaje con el número de categorías encontradas. - mapResp['data'] = listCategories; // Asigna los datos de las categorías a la respuesta. + var decodeResp = json.decode(respGet['body']); + List listCategories = CategoryModel.fromJsonArray(decodeResp['data']); + mapResp['ok'] = true; + mapResp['message'] = "${listCategories.length} categorías encontradas"; + mapResp['data'] = listCategories; } catch (e) { - mapResp['message'] = "Error en operador $e"; // Captura y asigna cualquier error durante la decodificación. + mapResp['message'] = "Error en decodificación: $e"; } } else { - mapResp['message'] = "${respGet['body']}"; // Asigna el mensaje de error de la API a la respuesta. + mapResp['message'] = "${respGet['body']}"; + } + } + } + + return mapResp; + } + + // Método para agregar una categoría + Future> addCategory(CategoryModel category) async { + Map mapResp = { + 'ok': false, + 'message': 'No se pudo agregar la categoría' + }; + + ConnectivityResult connectivityResult = (await _connectivity.checkConnectivity()); + + if (connectivityResult != ConnectivityResult.none) { + if (connectivityResult == ConnectivityResult.wifi || connectivityResult == ConnectivityResult.mobile) { + CategoryService categoryApi = CategoryService(); + Map respPost = await categoryApi.postCategory(category); + + if (respPost['statusCode'] == 201) { + mapResp['ok'] = true; + mapResp['message'] = 'Categoría agregada exitosamente'; + } else { + mapResp['message'] = "${respPost['body']}"; } } } - return mapResp; // Retorna la respuesta + return mapResp; } } diff --git a/lib/src/http_api/category_service.dart b/lib/src/http_api/category_service.dart index e3bc062..f2f2d97 100644 --- a/lib/src/http_api/category_service.dart +++ b/lib/src/http_api/category_service.dart @@ -1,23 +1,66 @@ +import 'dart:convert'; // Para convertir datos a JSON import 'package:flutter/foundation.dart'; import 'package:http/http.dart' as http; import 'package:primer_practica/environments/urls.dart' as api; +import 'package:primer_practica/src/models/categoryModel.dart'; class CategoryService { static const String apiBaseUrl = 'categoria'; // Método para obtener las categorías Future> getCategories({int offset = 0, int max = 100}) async { - String url = '${api.apiApp}/$apiBaseUrl?offset=$offset&max=$max'; + final String url = '${api.apiApp}/$apiBaseUrl?offset=$offset&max=$max'; if (kDebugMode) { print('Url -> $url'); } try { - final resp = await http.get(Uri.parse(url)); - return {"statusCode": resp.statusCode, "body": resp.body}; + final response = await http.get(Uri.parse(url)); + return { + 'statusCode': response.statusCode, + 'body': response.body, + }; } catch (e) { - return {"statusCode": 501, "body": '$e'}; + return { + 'statusCode': 501, + 'body': '$e', + }; } } + + // Método para enviar una nueva categoría al servidor + Future> postCategory(CategoryModel category) async { + final String url = '${api.apiApp}/$apiBaseUrl'; + + //conversión del objeto a Json + final categoryJson = category.toJson(); + + // Imprime la URL y el cuerpo de la solicitud + if (kDebugMode) { + print('Url -> $url'); + print('Body -> $categoryJson'); + } + + try { + // Realiza la solicitud POST al servidor + final response = await http.post( + Uri.parse(url), // Convierte la URL a un objeto Uri + headers: {'Content-Type': 'application/json'}, // Establece el tipo de contenido como JSON + body: json.encode(categoryJson), + ); + + return { + 'statusCode': response.statusCode, + 'body': response.body, + }; + } catch (e) { + + return { + 'statusCode': 501, + 'body': '$e', + }; + } + } + } diff --git a/lib/src/models/categoryModel.dart b/lib/src/models/categoryModel.dart index 8665a89..c3e6e44 100644 --- a/lib/src/models/categoryModel.dart +++ b/lib/src/models/categoryModel.dart @@ -4,8 +4,8 @@ class CategoryModel { int id; int? version; String? key; - String? name; - int? createdDate; + String name; + int createdDate; CategoryModel? parentCategory; List? subCategories; bool? active; @@ -14,8 +14,8 @@ class CategoryModel { required this.id, this.version, this.key, - this.name, - this.createdDate, + required this.name, + required this.createdDate, this.parentCategory, this.subCategories, this.active, diff --git a/lib/src/pages/formulario_categoria.dart b/lib/src/pages/formulario_categoria.dart index 07e4d52..efc0cc9 100644 --- a/lib/src/pages/formulario_categoria.dart +++ b/lib/src/pages/formulario_categoria.dart @@ -1,4 +1,7 @@ import 'package:flutter/material.dart'; +import 'package:primer_practica/src/controllers/categoty_controller.dart'; +import 'package:primer_practica/src/models/categoryModel.dart'; +import 'package:primer_practica/src/config/routes.dart'; class FormularioCategoria extends StatefulWidget { const FormularioCategoria({super.key}); @@ -10,6 +13,7 @@ class FormularioCategoria extends StatefulWidget { class _FormularioCategoriaState extends State { final _nombreController = TextEditingController(); final _claveController = TextEditingController(); + final CategoryController _categoryController = CategoryController(); // Instancia del controlador @override void dispose() { @@ -18,12 +22,11 @@ class _FormularioCategoriaState extends State { super.dispose(); } - void _guardarCategoria() { - final nombre = _nombreController.text; // se obtiene el calor de nombre y clave + Future _guardarCategoria() async { + final nombre = _nombreController.text; // Obtiene el valor de nombre y clave final clave = _claveController.text; if (nombre.isEmpty || clave.isEmpty) { - ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Por favor, complete todos los campos')), ); @@ -32,15 +35,27 @@ class _FormularioCategoriaState extends State { final fechaCreado = DateTime.now().millisecondsSinceEpoch; - final categoria = { - "clave": clave, - "fechaCreado": fechaCreado, - "nombre": nombre, - }; + final categoria = CategoryModel( + id: 0, + key: clave, + name: nombre, + createdDate: fechaCreado, + ); + + final result = await _categoryController.addCategory(categoria); // Llama al método para agregar categoría - print(categoria); + if (result['ok']) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(result['message'])), // Muestra mensaje de éxito + ); - Navigator.pop(context); + Navigator.pop(context); + Navigator.pushNamed(context, 'home'); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(result['message'])), + ); + } } @override @@ -50,7 +65,7 @@ class _FormularioCategoriaState extends State { title: const Text('Agregar Categoría'), ), body: Padding( - padding: const EdgeInsets.all(16.0), + padding: const EdgeInsets.all(16.0), // Ajuste del padding para un diseño más estético child: Column( children: [ TextField( @@ -58,13 +73,13 @@ class _FormularioCategoriaState extends State { decoration: const InputDecoration(labelText: 'Clave'), keyboardType: TextInputType.text, ), - const SizedBox(height: 16), + const SizedBox(height: 16), // Ajuste del espacio entre campos TextField( controller: _nombreController, decoration: const InputDecoration(labelText: 'Nombre'), keyboardType: TextInputType.text, ), - const SizedBox(height: 16), + const SizedBox(height: 24), // Ajuste del espacio entre campos y botón ElevatedButton( onPressed: _guardarCategoria, child: const Text('GUARDAR'), -- libgit2 0.27.1