Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
P
primera_practica
Project
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Yenisleydi Benitez Martinez
primera_practica
Commits
abd13ab8
Commit
abd13ab8
authored
Aug 02, 2024
by
yenisleydi
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
categoria api
parent
c4971193
Show whitespace changes
Inline
Side-by-side
Showing
4 changed files
with
118 additions
and
38 deletions
+118
-38
categoty_controller.dart
lib/src/controllers/categoty_controller.dart
+40
-18
category_service.dart
lib/src/http_api/category_service.dart
+47
-4
categoryModel.dart
lib/src/models/categoryModel.dart
+4
-4
formulario_categoria.dart
lib/src/pages/formulario_categoria.dart
+27
-12
No files found.
lib/src/controllers/categoty_controller.dart
View file @
abd13ab8
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:connectivity_plus/connectivity_plus.dart'
;
import
'package:primer_practica/src/http_api/category_service.dart'
;
import
'package:primer_practica/src/http_api/category_service.dart'
;
import
'package:primer_practica/src/models/categoryModel.dart'
;
import
'package:primer_practica/src/models/categoryModel.dart'
;
class
CategoryController
{
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
<
Map
<
String
,
dynamic
>>
getCategories
()
async
{
Future
<
Map
<
String
,
dynamic
>>
getCategories
()
async
{
// Inicializa la respuesta por defecto.
Map
<
String
,
dynamic
>
mapResp
=
{
Map
<
String
,
dynamic
>
mapResp
=
{
'ok'
:
false
,
'ok'
:
false
,
'message'
:
'No hay categorias'
,
'message'
:
'No hay categorias'
,
'data'
:
null
'data'
:
null
};
};
// Verifica la conectividad.
ConnectivityResult
connectivityResult
=
(
await
_connectivity
.
checkConnectivity
());
ConnectivityResult
connectivityResult
=
(
await
_connectivity
.
checkConnectivity
())
as
ConnectivityResult
;
// Si hay conexión a internet.
if
(
connectivityResult
!=
ConnectivityResult
.
none
)
{
if
(
connectivityResult
!=
ConnectivityResult
.
none
)
{
if
(
connectivityResult
==
ConnectivityResult
.
wifi
||
connectivityResult
==
ConnectivityResult
.
mobile
)
{
if
(
connectivityResult
==
ConnectivityResult
.
wifi
||
connectivityResult
==
ConnectivityResult
.
mobile
)
{
CategoryService
categoryApi
=
CategoryService
();
// Crea una instancia de CategoryApi.
CategoryService
categoryApi
=
CategoryService
();
Map
<
String
,
dynamic
>
respGet
=
await
categoryApi
.
getCategories
();
// Obtiene las categorías desde la API.
Map
<
String
,
dynamic
>
respGet
=
await
categoryApi
.
getCategories
();
// Si la respuesta de la API es exitosa.
if
(
respGet
[
'statusCode'
]
==
200
)
{
if
(
respGet
[
'statusCode'
]
==
200
)
{
try
{
try
{
var
decodeResp
=
json
.
decode
(
respGet
[
'body'
]);
// Decodifica la respuesta JSON.
var
decodeResp
=
json
.
decode
(
respGet
[
'body'
]);
List
<
CategoryModel
>
listCategories
=
CategoryModel
.
fromJsonArray
(
decodeResp
[
'data'
]);
// Convierte los datos en una lista de categorías.
List
<
CategoryModel
>
listCategories
=
CategoryModel
.
fromJsonArray
(
decodeResp
[
'data'
]);
mapResp
[
'ok'
]
=
true
;
// Marca la operación como exitosa.
mapResp
[
'ok'
]
=
true
;
mapResp
[
'message'
]
=
"
${listCategories.length}
categor
ias encontradas"
;
// Actualiza el mensaje con el número de categorías encontradas.
mapResp
[
'message'
]
=
"
${listCategories.length}
categor
ías encontradas"
;
mapResp
[
'data'
]
=
listCategories
;
// Asigna los datos de las categorías a la respuesta.
mapResp
[
'data'
]
=
listCategories
;
}
catch
(
e
)
{
}
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']}
"
;
}
}
}
}
return
mapResp
;
}
// Método para agregar una categoría
Future
<
Map
<
String
,
dynamic
>>
addCategory
(
CategoryModel
category
)
async
{
Map
<
String
,
dynamic
>
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
<
String
,
dynamic
>
respPost
=
await
categoryApi
.
postCategory
(
category
);
if
(
respPost
[
'statusCode'
]
==
201
)
{
mapResp
[
'ok'
]
=
true
;
mapResp
[
'message'
]
=
'Categoría agregada exitosamente'
;
}
else
{
}
else
{
mapResp
[
'message'
]
=
"
${resp
Get['body']}
"
;
// Asigna el mensaje de error de la API a la respuesta.
mapResp
[
'message'
]
=
"
${resp
Post['body']}
"
;
}
}
}
}
}
}
return
mapResp
;
// Retorna la respuesta
return
mapResp
;
}
}
}
}
lib/src/http_api/category_service.dart
View file @
abd13ab8
import
'dart:convert'
;
// Para convertir datos a JSON
import
'package:flutter/foundation.dart'
;
import
'package:flutter/foundation.dart'
;
import
'package:http/http.dart'
as
http
;
import
'package:http/http.dart'
as
http
;
import
'package:primer_practica/environments/urls.dart'
as
api
;
import
'package:primer_practica/environments/urls.dart'
as
api
;
import
'package:primer_practica/src/models/categoryModel.dart'
;
class
CategoryService
{
class
CategoryService
{
static
const
String
apiBaseUrl
=
'categoria'
;
static
const
String
apiBaseUrl
=
'categoria'
;
// Método para obtener las categorías
// Método para obtener las categorías
Future
<
Map
<
String
,
dynamic
>>
getCategories
({
int
offset
=
0
,
int
max
=
100
})
async
{
Future
<
Map
<
String
,
dynamic
>>
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
)
{
if
(
kDebugMode
)
{
print
(
'Url ->
$url
'
);
print
(
'Url ->
$url
'
);
}
}
try
{
try
{
final
resp
=
await
http
.
get
(
Uri
.
parse
(
url
));
final
response
=
await
http
.
get
(
Uri
.
parse
(
url
));
return
{
"statusCode"
:
resp
.
statusCode
,
"body"
:
resp
.
body
};
return
{
'statusCode'
:
response
.
statusCode
,
'body'
:
response
.
body
,
};
}
catch
(
e
)
{
}
catch
(
e
)
{
return
{
"statusCode"
:
501
,
"body"
:
'
$e
'
};
return
{
'statusCode'
:
501
,
'body'
:
'
$e
'
,
};
}
}
}
}
// Método para enviar una nueva categoría al servidor
Future
<
Map
<
String
,
dynamic
>>
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
'
,
};
}
}
}
}
lib/src/models/categoryModel.dart
View file @
abd13ab8
...
@@ -4,8 +4,8 @@ class CategoryModel {
...
@@ -4,8 +4,8 @@ class CategoryModel {
int
id
;
int
id
;
int
?
version
;
int
?
version
;
String
?
key
;
String
?
key
;
String
?
name
;
String
name
;
int
?
createdDate
;
int
createdDate
;
CategoryModel
?
parentCategory
;
CategoryModel
?
parentCategory
;
List
<
CategoryModel
>?
subCategories
;
List
<
CategoryModel
>?
subCategories
;
bool
?
active
;
bool
?
active
;
...
@@ -14,8 +14,8 @@ class CategoryModel {
...
@@ -14,8 +14,8 @@ class CategoryModel {
required
this
.
id
,
required
this
.
id
,
this
.
version
,
this
.
version
,
this
.
key
,
this
.
key
,
this
.
name
,
required
this
.
name
,
this
.
createdDate
,
required
this
.
createdDate
,
this
.
parentCategory
,
this
.
parentCategory
,
this
.
subCategories
,
this
.
subCategories
,
this
.
active
,
this
.
active
,
...
...
lib/src/pages/formulario_categoria.dart
View file @
abd13ab8
import
'package:flutter/material.dart'
;
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
{
class
FormularioCategoria
extends
StatefulWidget
{
const
FormularioCategoria
({
super
.
key
});
const
FormularioCategoria
({
super
.
key
});
...
@@ -10,6 +13,7 @@ class FormularioCategoria extends StatefulWidget {
...
@@ -10,6 +13,7 @@ class FormularioCategoria extends StatefulWidget {
class
_FormularioCategoriaState
extends
State
<
FormularioCategoria
>
{
class
_FormularioCategoriaState
extends
State
<
FormularioCategoria
>
{
final
_nombreController
=
TextEditingController
();
final
_nombreController
=
TextEditingController
();
final
_claveController
=
TextEditingController
();
final
_claveController
=
TextEditingController
();
final
CategoryController
_categoryController
=
CategoryController
();
// Instancia del controlador
@override
@override
void
dispose
()
{
void
dispose
()
{
...
@@ -18,12 +22,11 @@ class _FormularioCategoriaState extends State<FormularioCategoria> {
...
@@ -18,12 +22,11 @@ class _FormularioCategoriaState extends State<FormularioCategoria> {
super
.
dispose
();
super
.
dispose
();
}
}
void
_guardarCategoria
()
{
Future
<
void
>
_guardarCategoria
()
async
{
final
nombre
=
_nombreController
.
text
;
//
se obtiene el c
alor de nombre y clave
final
nombre
=
_nombreController
.
text
;
//
Obtiene el v
alor de nombre y clave
final
clave
=
_claveController
.
text
;
final
clave
=
_claveController
.
text
;
if
(
nombre
.
isEmpty
||
clave
.
isEmpty
)
{
if
(
nombre
.
isEmpty
||
clave
.
isEmpty
)
{
ScaffoldMessenger
.
of
(
context
).
showSnackBar
(
ScaffoldMessenger
.
of
(
context
).
showSnackBar
(
const
SnackBar
(
content:
Text
(
'Por favor, complete todos los campos'
)),
const
SnackBar
(
content:
Text
(
'Por favor, complete todos los campos'
)),
);
);
...
@@ -32,15 +35,27 @@ class _FormularioCategoriaState extends State<FormularioCategoria> {
...
@@ -32,15 +35,27 @@ class _FormularioCategoriaState extends State<FormularioCategoria> {
final
fechaCreado
=
DateTime
.
now
().
millisecondsSinceEpoch
;
final
fechaCreado
=
DateTime
.
now
().
millisecondsSinceEpoch
;
final
categoria
=
{
final
categoria
=
CategoryModel
(
"clave"
:
clave
,
id:
0
,
"fechaCreado"
:
fechaCreado
,
key:
clave
,
"nombre"
:
nombre
,
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
@override
...
@@ -50,7 +65,7 @@ class _FormularioCategoriaState extends State<FormularioCategoria> {
...
@@ -50,7 +65,7 @@ class _FormularioCategoriaState extends State<FormularioCategoria> {
title:
const
Text
(
'Agregar Categoría'
),
title:
const
Text
(
'Agregar Categoría'
),
),
),
body:
Padding
(
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
(
child:
Column
(
children:
<
Widget
>[
children:
<
Widget
>[
TextField
(
TextField
(
...
@@ -58,13 +73,13 @@ class _FormularioCategoriaState extends State<FormularioCategoria> {
...
@@ -58,13 +73,13 @@ class _FormularioCategoriaState extends State<FormularioCategoria> {
decoration:
const
InputDecoration
(
labelText:
'Clave'
),
decoration:
const
InputDecoration
(
labelText:
'Clave'
),
keyboardType:
TextInputType
.
text
,
keyboardType:
TextInputType
.
text
,
),
),
const
SizedBox
(
height:
16
),
const
SizedBox
(
height:
16
),
// Ajuste del espacio entre campos
TextField
(
TextField
(
controller:
_nombreController
,
controller:
_nombreController
,
decoration:
const
InputDecoration
(
labelText:
'Nombre'
),
decoration:
const
InputDecoration
(
labelText:
'Nombre'
),
keyboardType:
TextInputType
.
text
,
keyboardType:
TextInputType
.
text
,
),
),
const
SizedBox
(
height:
16
),
const
SizedBox
(
height:
24
),
// Ajuste del espacio entre campos y botón
ElevatedButton
(
ElevatedButton
(
onPressed:
_guardarCategoria
,
onPressed:
_guardarCategoria
,
child:
const
Text
(
'GUARDAR'
),
child:
const
Text
(
'GUARDAR'
),
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment