In Flutter, to create a TextFormField with a hidden input type, similar to an HTML input type="hidden", you can use the Visibility widget in conjunction with TextFormField.
Here's how to achieve this:
Wrap the TextFormField in a Visibility widget:
Set the visible property of the Visibility widget to false. This will hide the TextFormField from the user interface.
Set maintainState to true:
Within the Visibility widget, set maintainState: true. This crucial step ensures that even though the TextFormField is not visible, its state is preserved, allowing you to still access its value through a TextEditingController.
Use a TextEditingController:
Attach a TextEditingController to your TextFormField. This controller will allow you to programmatically set and retrieve the text value of the hidden field.
Example:
import 'package:flutter/material.dart';class HiddenTextFieldScreen extends StatefulWidget { @override _HiddenTextFieldScreenState createState() => _HiddenTextFieldScreenState();}class _HiddenTextFieldScreenState extends State<HiddenTextFieldScreen> { final TextEditingController _hiddenController = TextEditingController(); @override void initState() { super.initState(); // Set an initial value for the hidden field _hiddenController.text = "This is a hidden value"; } @override void dispose() { _hiddenController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Hidden TextFormField'), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ Visibility( visible: false, // Makes the TextFormField invisible maintainState: true, // Preserves the state and value child: TextFormField( controller: _hiddenController, ), ), ElevatedButton( onPressed: () { // Access the value of the hidden field print('Hidden field value: ${_hiddenController.text}'); }, child: Text('Get Hidden Value'), ), ], ), ), ); }}
In this example, the TextFormField is not displayed on the screen, but its value
can still be accessed and manipulated using _hiddenController.
This approach effectively mimics the behavior of an HTML input type="hidden" field.
Comments
Post a Comment