Commit 8b3ebbf3 by yenisleydi

modificaciones

parent d72543d6
...@@ -2,7 +2,7 @@ import 'package:flutter/material.dart'; ...@@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
import 'package:primer_practica/src/pages/formulario_categoria.dart'; import 'package:primer_practica/src/pages/formulario_categoria.dart';
import 'package:primer_practica/src/pages/login_page.dart'; import 'package:primer_practica/src/pages/login_page.dart';
import 'package:primer_practica/src/pages/home_page.dart'; import 'package:primer_practica/src/pages/home_page.dart';
import 'package:primer_practica/src/pages/articles_page.dart';
Map<String, WidgetBuilder> getApplicationRoutes() { Map<String, WidgetBuilder> getApplicationRoutes() {
return <String, WidgetBuilder>{ return <String, WidgetBuilder>{
......
import 'dart:convert'; import 'dart:convert';
import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:primer_practica/src/models/articles_model.dart'; import 'package:primer_practica/src/models/articles_model.dart';
import '../http_api/articles_api.dart'; import '../http_api/articles_api.dart';
class ArticleController { class ArticleController {
...@@ -38,4 +37,32 @@ class ArticleController { ...@@ -38,4 +37,32 @@ class ArticleController {
return mapResp; return mapResp;
} }
Future<List<ArticlesModel>> searchArticles(String query) async {
List<ArticlesModel> listArticles = [];
ConnectivityResult connectivityResult = await _connectivity.checkConnectivity();
if (connectivityResult != ConnectivityResult.none) {
if (connectivityResult == ConnectivityResult.wifi || connectivityResult == ConnectivityResult.mobile) {
Map<String, dynamic> respGet = await _articleApi.searchArticles(query);
if (respGet['statusCode'] == 200) {
try {
var decodeResp = json.decode(respGet['body']);
listArticles = ArticlesModel.fromJsonArray(decodeResp['data']);
} catch (e) {
throw Exception("Error en el procesamiento de datos: $e");
}
} else {
throw Exception("Error en la respuesta de la API: ${respGet['body']}");
}
} else {
throw Exception("No hay conectividad");
}
} else {
throw Exception("No hay conectividad");
}
return listArticles;
}
} }
...@@ -54,7 +54,7 @@ class CategoryController { ...@@ -54,7 +54,7 @@ class CategoryController {
CategoryService categoryApi = CategoryService(); CategoryService categoryApi = CategoryService();
Map<String, dynamic> respPost = await categoryApi.postCategory(category); Map<String, dynamic> respPost = await categoryApi.postCategory(category);
if (respPost['statusCode'] == 201) { if (respPost['statusCode'] == 201 || respPost['statusCode'] == 200) {
mapResp['ok'] = true; mapResp['ok'] = true;
mapResp['message'] = 'Categoría agregada exitosamente'; mapResp['message'] = 'Categoría agregada exitosamente';
} else { } else {
......
import 'package:flutter/material.dart';
import 'package:primer_practica/src/controllers/articles_controller.dart';
import 'package:primer_practica/src/models/articles_model.dart';
class ArticleSearchDelegate extends SearchDelegate {
final ArticleController articleCtrl = ArticleController();
ArticleSearchDelegate() : super();
@override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = '';
},
),
];
}
@override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
onPressed: () {
close(context, null);
},
);
}
@override
Widget buildResults(BuildContext context) {
return Container();
}
@override
Widget buildSuggestions(BuildContext context) {
if (query.isEmpty) {
return Center(child: Text('Ingrese el texto para buscar artículos.'));
}
return FutureBuilder<List<ArticlesModel>>(
future: articleCtrl.searchArticles(query),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return Center(child: Text('No se encontraron artículos.'));
} else {
final articles = snapshot.data!;
return ListView.builder(
itemCount: articles.length,
itemBuilder: (context, index) {
final article = articles[index];
return ListTile(
title: Text(article.nombre),
subtitle: Text(article.precios.isNotEmpty
? '\$${article.precios[0].precio.toStringAsFixed(2)}'
: 'Sin precio'),
trailing: IconButton(
icon: Icon(Icons.shopping_cart),
onPressed: () {
close(context, null); // Cierra el SearchDelegate
},
),
);
},
);
}
},
);
}
}
...@@ -4,7 +4,6 @@ import 'package:primer_practica/environments/urls.dart' as api; ...@@ -4,7 +4,6 @@ import 'package:primer_practica/environments/urls.dart' as api;
class ArticlesApi { class ArticlesApi {
Future<Map<String, dynamic>> getArticles() async { Future<Map<String, dynamic>> getArticles() async {
// Usa la constante `apiBaseUrl` de `urls.dart` para construir la URL
String url = '${api.apiApp}/articulo?offset=0&max=100'; String url = '${api.apiApp}/articulo?offset=0&max=100';
if (kDebugMode) { if (kDebugMode) {
...@@ -18,4 +17,19 @@ class ArticlesApi { ...@@ -18,4 +17,19 @@ class ArticlesApi {
return {"statusCode": 501, "body": '$e'}; return {"statusCode": 501, "body": '$e'};
} }
} }
Future<Map<String, dynamic>> searchArticles(String query) async {
String url = '${api.apiApp}/articulo?nombre="$query"';
if (kDebugMode) {
print('Url -> $url');
}
try {
final resp = await http.get(Uri.parse(url));
return {"statusCode": resp.statusCode, "body": resp.body};
} catch (e) {
return {"statusCode": 501, "body": '$e'};
}
}
} }
...@@ -23,7 +23,7 @@ class ListaCategorias extends StatelessWidget { ...@@ -23,7 +23,7 @@ class ListaCategorias extends StatelessWidget {
CategoryModel category = snapshot.data!['data'][index]; CategoryModel category = snapshot.data!['data'][index];
return Card( return Card(
child: ListTile( child: ListTile(
title: Text(category.name?? 'No Name'), // Muestra el nombre de la categoría title: Text(category.name), // Muestra el nombre de la categoría
leading: const Icon(Icons.touch_app), leading: const Icon(Icons.touch_app),
onTap: () { onTap: () {
Navigator.push( Navigator.push(
......
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:primer_practica/src/controllers/categoty_controller.dart'; import 'package:primer_practica/src/controllers/categoty_controller.dart';
import 'package:primer_practica/src/models/categoryModel.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});
...@@ -48,8 +48,8 @@ class _FormularioCategoriaState extends State<FormularioCategoria> { ...@@ -48,8 +48,8 @@ class _FormularioCategoriaState extends State<FormularioCategoria> {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(result['message'])), // Muestra mensaje de éxito SnackBar(content: Text(result['message'])), // Muestra mensaje de éxito
); );
print("hola");
Navigator.pop(context); //Navigator.pop(context);
Navigator.pushNamed(context, 'home'); Navigator.pushNamed(context, 'home');
} else { } else {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
...@@ -65,7 +65,7 @@ class _FormularioCategoriaState extends State<FormularioCategoria> { ...@@ -65,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), // Ajuste del padding para un diseño más estético padding: const EdgeInsets.all(170.0),
child: Column( child: Column(
children: <Widget>[ children: <Widget>[
TextField( TextField(
...@@ -73,13 +73,13 @@ class _FormularioCategoriaState extends State<FormularioCategoria> { ...@@ -73,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), // Ajuste del espacio entre campos const SizedBox(height: 50),
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: 24), // Ajuste del espacio entre campos y botón const SizedBox(height: 60), // Ajuste del espacio entre campos y botón
ElevatedButton( ElevatedButton(
onPressed: _guardarCategoria, onPressed: _guardarCategoria,
child: const Text('GUARDAR'), child: const Text('GUARDAR'),
......
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:primer_practica/src/pages/category/lista_categorias.dart'; import 'package:primer_practica/src/pages/category/lista_categorias.dart';
import 'package:primer_practica/src/delegates/article_search_delegate.dart';
class HomePage extends StatelessWidget { class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key); const HomePage({Key? key}) : super(key: key);
...@@ -14,7 +15,10 @@ class HomePage extends StatelessWidget { ...@@ -14,7 +15,10 @@ class HomePage extends StatelessWidget {
IconButton( IconButton(
icon: const Icon(Icons.search), icon: const Icon(Icons.search),
onPressed: () { onPressed: () {
// Acción de búsqueda showSearch(
context: context,
delegate: ArticleSearchDelegate(),
);
}, },
) )
], ],
......
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