123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327 |
- import 'package:flutter/material.dart';
- import '../../themes/themes.dart'; // Asegúrate de tener este archivo con los temas correctos
- import '../../models/models.dart'; // Tus modelos de datos
- import '../../viewmodels/viewmodels.dart'; // Tus ViewModels
- class PedidoForm extends StatefulWidget {
- @override
- _PedidoFormState createState() => _PedidoFormState();
- }
- class ItemCarrito {
- Producto producto;
- int cantidad;
- ItemCarrito({required this.producto, this.cantidad = 1});
- }
- class _PedidoFormState extends State<PedidoForm> {
- CategoriaProductoViewModel cvm = CategoriaProductoViewModel();
- ProductoViewModel pvm = ProductoViewModel();
- bool _isLoading = false;
- ScrollController horizontalScrollController = ScrollController();
- CategoriaProducto? categoriaSeleccionada;
- List<CategoriaProducto> categorias = [];
- List<Producto> productos = [];
- List<ItemCarrito> carrito = [];
- double calcularTotalPedido() {
- double total = 0;
- for (var item in carrito) {
- total += double.parse(item.producto.precio!) * item.cantidad;
- }
- return total;
- }
- @override
- void initState() {
- super.initState();
- cargarCategoriasIniciales();
- }
- @override
- void dispose() {
- horizontalScrollController.dispose();
- super.dispose();
- }
- Future<void> cargarCategoriasIniciales() async {
- setState(() => _isLoading = true);
- var categoriasObtenidas = await cvm.getCategoriaProducto();
- setState(() {
- categorias = categoriasObtenidas;
- _isLoading = false;
- // Selecciona la primera categoría por defecto si hay categorías disponibles
- if (categorias.isNotEmpty) {
- categoriaSeleccionada = categorias.first;
- seleccionarCategoria(categoriaSeleccionada!);
- }
- });
- }
- Future<void> seleccionarCategoria(CategoriaProducto categoria) async {
- if (!mounted) return;
- setState(() {
- _isLoading = true;
- categoriaSeleccionada = categoria;
- });
- productos = await pvm.fetchRegistros(categoriaProducto: categoria);
- if (!mounted) return;
- setState(() => _isLoading = false);
- }
- void agregarAlCarrito(Producto producto) {
- setState(() {
- var indice =
- carrito.indexWhere((item) => item.producto.id == producto.id);
- if (indice != -1) {
- carrito[indice].cantidad++;
- } else {
- // Se agrega el nuevo producto al carrito con cantidad inicial de 1
- carrito.add(ItemCarrito(producto: producto));
- }
- });
- }
- void quitarDelCarrito(Producto producto) {
- setState(() {
- // Comienza con setState por la misma razón
- var indice =
- carrito.indexWhere((item) => item.producto.id == producto.id);
- if (indice != -1) {
- if (carrito[indice].cantidad > 1) {
- carrito[indice].cantidad--;
- } else {
- carrito.removeAt(indice);
- }
- }
- });
- }
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text("Crear Pedido"),
- ),
- body: Row(
- children: [
- Flexible(
- flex: 3,
- child: _buildCartSection(),
- ),
- SizedBox(width: 35),
- Flexible(
- flex: 7,
- child: _buildProductsSection(),
- ),
- ],
- ),
- );
- }
- Widget _buildTotalSection() {
- double total =
- calcularTotalPedido(); // Aquí llamarías a la función calcularTotalPedido
- return Padding(
- padding: const EdgeInsets.symmetric(horizontal: 8.0),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- const Text('Total',
- style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
- Text("\$${total.toStringAsFixed(2)}",
- style:
- const TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
- ],
- ),
- );
- }
- Widget _buildCartSection() {
- return Card(
- margin: const EdgeInsets.all(8.0),
- child: Column(
- children: [
- const Padding(
- padding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 16.0),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Text('Producto',
- style:
- TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
- Text('Cantidad',
- style:
- TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
- ],
- ),
- ),
- Expanded(
- child: ListView.builder(
- itemCount: carrito.length,
- itemBuilder: (context, index) {
- final item = carrito[index];
- return ListTile(
- title: Text(item.producto.nombre!),
- subtitle: Text('\$${item.producto.precio}'),
- trailing: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- IconButton(
- icon: const Icon(Icons.delete, color: Colors.red),
- onPressed: () => eliminarProductoDelCarrito(index),
- ),
- IconButton(
- icon: const Icon(Icons.remove),
- onPressed: () => quitarDelCarrito(item.producto),
- ),
- const SizedBox(width: 5),
- Text(
- '${item.cantidad}',
- style: const TextStyle(
- fontWeight: FontWeight.bold, fontSize: 14),
- ),
- const SizedBox(width: 5),
- IconButton(
- icon: const Icon(Icons.add),
- onPressed: () => agregarAlCarrito(item.producto),
- ),
- // Botón para eliminar el producto del carrito
- ],
- ),
- );
- },
- ),
- ),
- const Divider(
- thickness: 5,
- ),
- _buildTotalSection(),
- const SizedBox(height: 25),
- Padding(
- padding: const EdgeInsets.all(8.0),
- child: ElevatedButton(
- onPressed: () {
- // Aquí implementarías la lógica para finalizar el pedido
- },
- style: ElevatedButton.styleFrom(
- primary: AppTheme.primary,
- onPrimary: AppTheme.secondary,
- textStyle: const TextStyle(fontSize: 22),
- fixedSize: const Size(250, 50)),
- child: const Text('Finalizar Pedido'),
- ),
- ),
- ],
- ),
- );
- }
- void eliminarProductoDelCarrito(int index) {
- setState(() {
- carrito.removeAt(index);
- });
- }
- Widget _buildProductsSection() {
- // Asumiendo que tienes un método para obtener los productos según la categoría seleccionada
- return Column(
- children: [
- _buildCategoryButtons(),
- const SizedBox(height: 10),
- Expanded(
- child: GridView.builder(
- gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
- crossAxisCount: 3, // Número de columnas
- childAspectRatio: 3 / 2, // Proporción de cada tarjeta
- ),
- itemCount: productos.length,
- itemBuilder: (context, index) {
- final producto = productos[index];
- return Card(
- child: InkWell(
- onTap: () {
- setState(() {
- // Aquí manejas la adición de productos al carrito
- agregarAlCarrito(producto);
- });
- },
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- const Icon(Icons.fastfood, size: 80),
- const SizedBox(height: 8),
- Padding(
- padding: EdgeInsets.fromLTRB(30, 0, 30, 0),
- child: Text(
- producto.nombre ?? '',
- style: const TextStyle(
- fontSize: 16, fontWeight: FontWeight.bold),
- )),
- const SizedBox(height: 8),
- Text(
- '\$${producto.precio}',
- style: const TextStyle(
- fontSize: 16,
- fontWeight: FontWeight.bold,
- color: Color(0xFF008000)),
- ),
- ],
- ),
- ),
- );
- },
- ),
- ),
- ],
- );
- }
- Widget _buildCategoryButtons() {
- return Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- SizedBox(
- height: 50, // Altura para los botones
- child: Scrollbar(
- controller: horizontalScrollController,
- thumbVisibility: true,
- thickness: 5.0,
- child: ListView.builder(
- scrollDirection: Axis.horizontal,
- itemCount: categorias.length,
- controller: horizontalScrollController,
- itemBuilder: (context, index) {
- final categoria = categorias[index];
- bool esSeleccionada = categoriaSeleccionada?.id == categoria.id;
- return Padding(
- padding: const EdgeInsets.symmetric(horizontal: 4.0),
- child: ElevatedButton(
- onPressed: () => seleccionarCategoria(categoria),
- style: ElevatedButton.styleFrom(
- primary: esSeleccionada
- ? const Color(0xFFFF848F)
- : Colors.white,
- onPrimary: Colors.black,
- textStyle: const TextStyle(
- fontWeight: FontWeight.bold,
- ),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(18.0),
- side: BorderSide(
- color: esSeleccionada ? Colors.black : Colors.grey),
- ),
- ),
- child: Text(categoria.nombre ?? 'Sin nombre'),
- ),
- );
- },
- ),
- ),
- ),
- ],
- );
- }
- }
|