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.
CodePudding user response:
To capitalize every word, you can use the help of the substring
method:
String capitalize(String str) {
return str
.split(' ')
.map((word) => word.substring(0, 1).toUpperCase() word.substring(1))
.join(' ');
}
print(capitalize('john doe')); // John Doe
CodePudding user response:
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));
}
}
)
CodePudding user response:
Reading the title of this question makes me think that you only want to capitilize 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 capitilize subsequent words or not. With the caveat that after a period (.
) you will get a capitilize word by default, but able to change it obviously.