'Change the keyboard type for a TextFormField in a Form
I have a text form that accepts letters and numbers and the keyboard changes dynamically. It's working but when I delete the code, the numeric keyboard remains Here is the example
final _controller = TextEditingController();
var keyboardType = TextInputType.text;
FocusNode _focusNode = FocusNode();
TextFormField(
style: TextStyle(
color: Colors.black,
fontSize: 50,
fontWeight: FontWeight.w700),
decoration:
InputDecoration(labelText: "code", hintText: 'ABC1234'),
controller: _controller,
focusNode: _focusNode,
textCapitalization: TextCapitalization.characters,
keyboardType: keyboardType,
onChanged: (value) {
if (value.length == 3) {
FocusScope.of(context).unfocus();
setState(() {
keyboardType = TextInputType.number;
});
Future.delayed(Duration(milliseconds: 150)).then((value) {
FocusScope.of(context).requestFocus();
});
} else {
setState(() {
keyboardType = TextInputType.text;
});
}
}),
Solution 1:[1]
That's because it's already open. you will have to do the same steps you did to show it as a numeric keyboard
i.e
else {
FocusScope.of(context).unfocus();
setState(() {
keyboardType = TextInputType.text;
});
Future.delayed(Duration(milliseconds: 150)).then((value) {
FocusScope.of(context).requestFocus();
});
also, this way of handling the condition will result in closing and reopening of keyboard in many cases, you should make it as follows
if (value.length == 3 && keyboardType == TextInputType.text) {
//....
} else if (value.length < 3 && keyboardType != TextInput.text) {
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |