Below is a dialog to capture users input by using a textField and a button. The button is disabled when textField is empty, however it continues to become disabled when textField is filled with values. This is because the _textController.text state is not being updated (rendered again in this widget).
void _pushAdd() async {
await showDialog(
context: this.context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Add a custom word'),
content: _renderForm(),
actions: <Widget>[
FlatButton(
child: Text('ADD'),
onPressed: (_textController.text.isNotEmpty) ? () => _addNewPair() : null,
),
],
);
},
);
// Changed _pushAdd as async to handle onClose and clear _textController upon exit
_textController.clear();
Currently _textController is initiated within the class at the top (not init).
var _textController = new TextEditingController();
The textField with the _textController is located here:
Widget _renderForm() {
return Container(
height: 50.0,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
autofocus: true,
textCapitalization: TextCapitalization.words,
controller: _textController,
decoration: InputDecoration(
hintText: 'RedPotato',
),
),
]
)
);
}
My initial plan was to use an onChanged: + another state which stores the text. However I was doubtful if it was efficient to do that. So I ask, what is the standard way to handle TextField values real time so that other Widgets can listen to the changes?
You should use it in the onChanged callback like this! TextField( autofocus: true, textAlign: TextAlign. center, onChanged: (newText) { setState(() { newTaskTitle = newText; }); }, ), Now when a user types in the TextField, it will update the value.
onChanged is called before onSubmitted when user indicates completion of editing, such as when pressing the "done" button on the keyboard. That default behavior can be overridden. See onEditingComplete for details.
You just have to listen the TextEditingController
for text changes.
var _textController = TextEditingController();
@override
void dispose() {
// Clean up the controller when the Widget is disposed
_textController.dispose();
super.dispose();
}
@override
void initState() {
_textController.addListener((){
//here you have the changes of your textfield
print("value: ${_textController.text}");
//use setState to rebuild the widget
setState(() {
});
});
super.initState();
}
For more info check this link : https://flutter.io/docs/cookbook/forms/retrieve-input
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With