Obtener el valor de un campo de texto
Cómo recuperar texto de un campo de texto.
En esta receta, aprenderás cómo recuperar el texto que un usuario ha ingresado en un campo de texto siguiendo estos pasos:
- Crear un
TextEditingController. - Asignar el
TextEditingControllera unTextField. - Mostrar el valor actual del campo de texto.
1. Crear un TextEditingController
#
Para recuperar el texto que un usuario ha ingresado en un campo de texto,
crea un TextEditingController
y asígnalo a un TextField o TextFormField.
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
// Define a corresponding State class.
// This class holds the data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
// Create a text controller and use it to retrieve the current value
// of the TextField.
final myController = TextEditingController();
@override
void dispose() {
// Clean up the controller when the widget is disposed.
myController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// Fill this out in the next step.
}
}
2. Asignar el TextEditingController a un TextField
#
Ahora que tienes un TextEditingController, conéctalo
a un campo de texto usando la propiedad controller:
return TextField(controller: myController);
3. Mostrar el valor actual del campo de texto
#Después de asignar el TextEditingController al campo de texto,
comienza a leer los valores. Utiliza la propiedad text
proporcionada por el TextEditingController para recuperar el
String que el usuario ha ingresado en el campo de texto.
El siguiente código muestra un diálogo de alerta con el valor actual del campo de texto cuando el usuario toca un floating action button.
FloatingActionButton(
// When the user presses the button, show an alert dialog containing
// the text that the user has entered into the text field.
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
// Retrieve the text that the user has entered by using the
// TextEditingController.
content: Text(myController.text),
);
},
);
},
tooltip: 'Show me the value!',
child: const Icon(Icons.text_fields),
),
Ejemplo interactivo
#A menos que se indique lo contrario, la documentación de este sitio refleja Flutter 3.44.0. Página actualizada por última vez el 2026-05-05. Ver código fuente oreportar un problema.