Commit a1d4ef42 by Nayeli Monserrat Velasco Lopez

Merge branch 'nayeli.velasco' into 'master'

Crear categoria API See merge request !9
parents f5b6f189 0fdab128
...@@ -15,7 +15,7 @@ class ArticuloController { ...@@ -15,7 +15,7 @@ class ArticuloController {
}; };
// Verificar la conectividad de la red // Verificar la conectividad de la red
List<ConnectivityResult> connectivityResult = await _connectivity.checkConnectivity(); List<ConnectivityResult> connectivityResult = await _connectivity.checkConnectivity();
if (!connectivityResult.contains(ConnectivityResult.none)) { if (!connectivityResult.contains(ConnectivityResult.none)) {
if (connectivityResult.contains(ConnectivityResult.wifi) || connectivityResult.contains(ConnectivityResult.mobile)) { if (connectivityResult.contains(ConnectivityResult.wifi) || connectivityResult.contains(ConnectivityResult.mobile)) {
try { try {
......
...@@ -15,28 +15,67 @@ class CategoryController { ...@@ -15,28 +15,67 @@ class CategoryController {
'data': null 'data': null
}; };
// Verificar la conectividad de la red
List<ConnectivityResult> connectivityResult = await _connectivity.checkConnectivity(); List<ConnectivityResult> connectivityResult = await _connectivity.checkConnectivity();
if (!connectivityResult.contains(ConnectivityResult.none)) { if (!connectivityResult.contains(ConnectivityResult.none)) {
if (connectivityResult.contains(ConnectivityResult.wifi) || connectivityResult.contains(ConnectivityResult.mobile)) { if (connectivityResult.contains(ConnectivityResult.wifi) || connectivityResult.contains(ConnectivityResult.mobile)) {
try { try {
// Realizar la solicitud a la API
Map<String, dynamic> respGet = await _categoryApi.getCategories(); Map<String, dynamic> respGet = await _categoryApi.getCategories();
if (respGet['statusCode'] == 200) { if (respGet['statusCode'] == 200) {
try { try {
var decodeResp = json.decode(respGet['body']); var decodeResp = json.decode(respGet['body']);
List<CategoriaModel> listCategories = CategoriaModel List<CategoriaModel> listCategories = CategoriaModel.fromJsonArray(decodeResp['data']);
.fromJsonArray(decodeResp['data']);
mapResp['ok'] = true; mapResp['ok'] = true;
mapResp['message'] = mapResp['message'] = "${listCategories.length} categorías encontradas";
"${listCategories.length} categorías encontradas";
mapResp['data'] = listCategories; mapResp['data'] = listCategories;
} catch (e) { } catch (e) {
mapResp['message'] = "Error en procesamiento de datos: $e"; mapResp['message'] = "Error en procesamiento de datos: $e";
} }
} else { } else {
mapResp['message'] = mapResp['message'] = "Error en la respuesta de la API: ${respGet['body']}";
"Error en la respuesta de la API: ${respGet['body']}"; }
} catch (e) {
mapResp['message'] = "Error en la solicitud a la API: $e";
}
} else {
mapResp['message'] = 'No hay conexión a internet';
}
} else {
mapResp['message'] = 'No hay conexión a internet';
}
return mapResp;
}
// Método para crear una categoría
Future<Map<String, dynamic>> createCategory(CategoriaModel categoria) async {
Map<String, dynamic> mapResp = {
'ok': false,
'message': 'No se pudo crear la categoría',
'data': null
};
List<ConnectivityResult> connectivityResult = await _connectivity.checkConnectivity();
if (!connectivityResult.contains(ConnectivityResult.none)) {
if (connectivityResult.contains(ConnectivityResult.wifi) || connectivityResult.contains(ConnectivityResult.mobile)) {
try {
Map<String, dynamic> respPost = await _categoryApi.postCategory(categoria);
if (respPost['statusCode'] == 200 || respPost['statusCode'] == 201) {
print('Regresa datos ');
try {
var decodeResp = json.decode(respPost['body']);
CategoriaModel newCategory = CategoriaModel.fromJson(decodeResp['data']);
mapResp['ok'] = true;
mapResp['message'] = "Categoría creada exitosamente";
mapResp['data'] = newCategory;
} catch (e) {
mapResp['message'] = "Error en procesamiento de datos: $e";
}
} else {
mapResp['message'] = "Error en la respuesta de la API: ${respPost['body']}";
} }
} catch (e) { } catch (e) {
mapResp['message'] = "Error en la solicitud a la API: $e"; mapResp['message'] = "Error en la solicitud a la API: $e";
......
...@@ -2,22 +2,19 @@ import 'dart:convert'; ...@@ -2,22 +2,19 @@ import 'dart:convert';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:miapp_flutter/environments/archivo.dart'; import 'package:miapp_flutter/environments/archivo.dart';
import 'package:miapp_flutter/src/models/CategoriaModel.dart';
class CategoryApi { class CategoryApi {
final String apiUrl = 'categoria'; // Asegúrate de que esta URL sea correcta
final String apiUrl = 'categoria';
// Método para obtener las categorías
Future<Map<String, dynamic>> getCategories() async { Future<Map<String, dynamic>> getCategories() async {
String url = '${apiApp}/$apiUrl?offset=0&max=100'; String url = '${apiApp}/$apiUrl?offset=0&max=100';
if (kDebugMode) { if (kDebugMode) {
print('Url -> $url'); print('Url -> $url');
} }
try { try {
final response = await http.get(Uri.parse(url)); final response = await http.get(Uri.parse(url));
// Verifica el estado de la respuesta
if (response.statusCode == 200) { if (response.statusCode == 200) {
return { return {
'statusCode': response.statusCode, 'statusCode': response.statusCode,
...@@ -36,4 +33,34 @@ class CategoryApi { ...@@ -36,4 +33,34 @@ class CategoryApi {
}; };
} }
} }
Future<Map<String, dynamic>> postCategory(CategoriaModel categoria) async {
String url = '$apiApp/$apiUrl';
if (kDebugMode) {
print('Url -> $url');
}
try {
final response = await http.post(
Uri.parse(url),
headers: {'Content-Type': 'application/json'},
body: json.encode(categoria.toJson()),
);
print('Status code: ${response.statusCode}');
print('Response body: ${response.body}');
return {
"statusCode": response.statusCode,
"body": response.body,
};
} catch (e) {
return {
"statusCode": 501,
"body": '$e',
};
}
}
} }
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:miapp_flutter/src/models/CategoriaModel.dart';
import 'dart:convert';
import '../controllers/CategoriaController.dart';
class NewCategoryPage extends StatefulWidget { class NewCategoryPage extends StatefulWidget {
const NewCategoryPage({Key? key}) : super(key: key); const NewCategoryPage({Key? key}) : super(key: key);
...@@ -14,7 +17,7 @@ class _NewCategoryPageState extends State<NewCategoryPage> { ...@@ -14,7 +17,7 @@ class _NewCategoryPageState extends State<NewCategoryPage> {
final _claveController = TextEditingController(); final _claveController = TextEditingController();
final _nombreController = TextEditingController(); final _nombreController = TextEditingController();
DateTime _selectedDate = DateTime.now(); DateTime _selectedDate = DateTime.now();
final _categoryController = CategoryController();
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
...@@ -71,15 +74,30 @@ class _NewCategoryPageState extends State<NewCategoryPage> { ...@@ -71,15 +74,30 @@ class _NewCategoryPageState extends State<NewCategoryPage> {
), ),
const SizedBox(height: 16.0), const SizedBox(height: 16.0),
ElevatedButton( ElevatedButton(
onPressed: () { onPressed: () async {
if (_formKey.currentState!.validate()) { if (_formKey.currentState!.validate()) {
int fechaCreado = _selectedDate.millisecondsSinceEpoch; CategoriaModel newCategory = CategoriaModel(
print({ id: 0,
"clave": _claveController.text, key: _claveController.text,
"fechaCreado": fechaCreado, name: _nombreController.text,
"nombre": _nombreController.text createdDate: _selectedDate.millisecondsSinceEpoch,
}); active: true,
Navigator.pop(context); );
var response = await _categoryController.createCategory(newCategory);
print('Datos de la categoría a enviar: ${json.encode(newCategory.toJson())}');
print(response);
if (response['statusCode'] == 200 || response['statusCode'] == 201) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error al crear categoría: ${response['body']}')),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Categoría creada con éxito')),
);
Navigator.pop(context);
}
} }
}, },
child: const Text('GUARDAR'), child: const Text('GUARDAR'),
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment