skip to Main Content

I have a search capability in my app, and I want the text input to be capitalized every time I start typing, but I cannot figure out how. In simpler terms, every time I start typing in my TextField, I want the first letter capitalized. Here is my current code:

 child: TextField(
       // Look into
       keyboardType: TextInputType.text,
       textCapitalization: TextCapitalization.none,
       autocorrect: true,
      )

I have tried using all of the TextCapitalization options, yet none worked, and I am not sure as to why. I’ve looked at other posts, and this usually seems to be the solution, yet it does not work for my app. Any help is appreciated.

2

Answers


  1. I have try using TextCapitalization.sentences, same as this answer

    TextField(
      // Look into
      keyboardType: TextInputType.text,
     textCapitalization: TextCapitalization.sentences,
     autocorrect: true,
    ),
    

    Result: image

    Login or Signup to reply.
  2. The textCapitalization option configures how the platform keyboard will select an uppercase or lowercase keyboard, so the behavior may depend on the platform. To have a TextField that always capitalizes the first letter of its value, you can make a custom TextEditingController and override its buildTextSpan method.

    A minimal example would be like this:

    class CapitalizedTextEditingController extends TextEditingController {
      @override
      TextSpan buildTextSpan({
        required BuildContext context,
        TextStyle? style,
        required bool withComposing,
      }) {
        final capitalizedText =
            text.isNotEmpty ? text[0].toUpperCase() + text.substring(1) : '';
        return TextSpan(text: capitalizedText);
      }
    }
    

    However, do take note that the original implementation of buildTextSpan is more complicated than this, so you might want to consider checking the base source code as well and implement this first letter capitalization logic based on it.

    You can then use the controller in your TextField:

    class _MyWidgetState extends State<MyWidget> {
      final controller = CapitalizedTextEditingController();
    
      // ...
    
      @override
      Widget build(BuildContext context) {
        return TextField(
          controller: controller,
        );
      }
    }
    

    References:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search