Flutter TextFormField TextCapitalization.words not working, in Android

140 Views Asked by At

I want to automatically capitalize the first letter when the user enters the first name. I use

` TextFormField(
 textCapitalization: TextCapitalization.words
     )`

works fine on IOS, but not on Android emulators or real phones.

use textCapitalization: TextCapitalization.words, expecting to capitalize the first letter both IOS and Android. Actual situation: Only IOS works normally;

  • Doctor summary (to see all details, run flutter doctor -v):
  • Flutter (Channel stable, 3.7.8, on macOS 13.2.1, 22D68, darwin-arm64, locale zh-Hans-AU)
  • Android toolchain: develop for Android devices (Android SDK version 33.0.2)
  • Xcode: develop for iOS and macOS (Xcode 14.2)
  • Chrome: develop for the web
  • Android Studio (version 2022.1)
  • VS Code (version 1.82.0)
  • Connected device (6 available)
  • Device emulator 5556 is offline.
  • HTTP Host Availability
  • No issues were found!
2

There are 2 best solutions below

1
Ibtissam AL Wannas On

To ensure consistent capitalization behaviour across both iOS and Android platforms, you can manually capitalize the first letter of the input text using a TextEditingController and the onChanged callback.

 class Home extends StatelessWidget {
      const Home({super.key});
    
      @override
      Widget build(BuildContext context) {
        TextEditingController nameController = TextEditingController();
        return Scaffold(
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextFormField(
                controller: nameController,
                onChanged: (text) {
                  // Ensure the first letter is capitalized
                  nameController.value = nameController.value.copyWith(
                    text: _capitalizeFirstLetter(text),
                    selection: TextSelection.collapsed(
                      offset: nameController.text.length,
                    ),
                  );
                },
                decoration: const InputDecoration(
                  labelText: 'First Name',
                ),
              )
            ],
          ),
        );
      }
    
      String _capitalizeFirstLetter(String text) {
        if (text.isEmpty) {
          return text;
        }
        return text[0].toUpperCase() + text.substring(1);
      }
    }
0
Warrio Mike On

or Enable these two properties of the text field should fix that:

textCapitalization: TextCapitalization.words,
keyboardType: TextInputType.text,