import 'package:flutter/material.dart'; import 'package:primer_practica/src/http_api/articles_api.dart'; // Asegúrate de importar la clase correcta class FormularioArticulos extends StatefulWidget { @override _FormularioArticulosState createState() => _FormularioArticulosState(); } class _FormularioArticulosState extends State { final _formKey = GlobalKey(); String _clave = ''; int _categoria = 1; String _nombre = ''; List _precios = [0.0, 0.0]; bool _activo = true; final ArticlesApi _articlesApi = ArticlesApi(); Future _guardarArticulo() async { if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); final result = await _articlesApi.addArticle( clave: _clave, categoria: _categoria, nombre: _nombre, precios: _precios, activo: _activo, ); if (result['statusCode'] == 200) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Artículo guardado exitosamente')), ); Navigator.pop(context); // Regresa a la lista de artículos } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Error al guardar el artículo')), ); } } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Formulario de Artículo'), ), body: Padding( padding: EdgeInsets.all(16.0), child: Form( key: _formKey, child: ListView( children: [ _buildTextField( label: 'Clave', onSaved: (value) => _clave = value!, inputType: TextInputType.text, ), _buildTextField( label: 'Categoría', onSaved: (value) => _categoria = int.parse(value!), inputType: TextInputType.number, ), _buildTextField( label: 'Nombre', onSaved: (value) => _nombre = value!, inputType: TextInputType.text, ), _buildTextField( label: 'Precio 1', onSaved: (value) => _precios[0] = double.parse(value!), inputType: TextInputType.number, ), _buildTextField( label: 'Precio 2', onSaved: (value) => _precios[1] = double.parse(value!), inputType: TextInputType.number, ), SizedBox(height: 30), Center( child: ElevatedButton( onPressed: _guardarArticulo, style: ElevatedButton.styleFrom( padding: EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0), textStyle: TextStyle(fontSize: 16), ), child: Text('Guardar'), ), ), ], ), ), ), ); } Widget _buildTextField({ required String label, required FormFieldSetter onSaved, required TextInputType inputType, }) { return Padding( padding: const EdgeInsets.symmetric(vertical: 12.0), child: TextFormField( decoration: InputDecoration( labelText: label, border: OutlineInputBorder(), contentPadding: EdgeInsets.symmetric(vertical: 15, horizontal: 10), ), keyboardType: inputType, onSaved: onSaved, validator: (value) { if (value == null || value.isEmpty) { return 'Este campo es obligatorio'; } return null; }, ), ); } }