Reputation: 172
Is there a way to automatically make the first word of text form field capital and after wards we can freely make the second word capital or small of our choice for Ex:- Steven Jhons
class UpperCaseTextFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
return TextEditingValue(
text: capitalize(newValue.text),
selection: newValue.selection,
);
}
}
String capitalize(String value) {
if (value.trim().isEmpty) {
return "";
} else if (value.isNotEmpty) {
return "${value[0].toUpperCase()}${value.substring(1).toLowerCase()}";
} else {
return "";
}
}
called it inside textformfield like this
TextFormField(
decoration:
const InputDecoration(hintText: "Name"),
controller: nameController,
validator: (value) {
if (value == null || value.isEmpty) {
return "Please enter your name";
} else {
return null;
}
},
textCapitalization: TextCapitalization.words,
inputFormatters: <TextInputFormatter>[
UpperCaseTextFormatter()
],
),
this is the code i have been using it makes the first word capital but we are not able to make the second or any word capital after ward need some help here thanks.
Upvotes: 1
Views: 111
Reputation: 8607
Reading the title of this question makes me think that you only want to capitalize the first word in a TextFormField, not every word? If that is so, why not just use:
textCapitalization: TextCapitalization.sentences
You will still have freedom afterwards to capitalize subsequent words or not. With the caveat that after a period (.
) you will get a capitalize word by default, but able to change it obviously.
Upvotes: 0
Reputation: 17762
You can try this to make the first letter to uppercase
TextFormField(
controller: _textEditingController,
onChange: (val){
if(_textEditingController.length > 0)
{
_textEditingController.text = "${_textEditingController[0].toUpperCase()}${
_textEditingController.substring(1)}";
_textController.selection = TextSelection.fromPosition(TextPosition(offset: _textController.text.length));
}
}
)
Upvotes: 1