Flutter textformfield uppercase

Flutter TextFormField Uppercase

To make a TextFormField in Flutter automatically convert input to uppercase, you can use the inputFormatters property
and provide an array of formatters. An example of using an uppercase input formatter is shown below:

    
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class UppercaseTextFormField extends StatelessWidget {
  final TextEditingController _textEditingController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: _textEditingController,
      inputFormatters: [UpperCaseTextFormatter()], // Add the formatter here
      decoration: InputDecoration(
        labelText: 'Uppercase Input',
      ),
    );
  }
}

class UpperCaseTextFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    return TextEditingValue(
      text: newValue.text.toUpperCase(),
      selection: newValue.selection,
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text('Uppercase TextFormField Example'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: [
            UppercaseTextFormField(),
            SizedBox(height: 16.0),
            ElevatedButton(
              onPressed: () {
                print("The value entered is: ${UpperCaseTextFormatter().formatEditUpdate(TextEditingValue.empty, _textEditingController.value)}");
              },
              child: Text('Print Value'),
            ),
          ],
        ),
      ),
    ),
  ));
}
    
  

In the provided example, a custom UpperCaseTextFormatter class is created by extending
TextInputFormatter. The formatEditUpdate method of the formatter is overridden to convert
the new text value to uppercase and maintain the selection of the text. The formatEditUpdate method
returns a TextEditingValue object containing the formatted text and selection.

The UppercaseTextFormField widget is then used to represent the TextFormField with the added
UpperCaseTextFormatter. The inputFormatters property of the TextFormField is assigned an array
containing the UpperCaseTextFormatter. This formatter will automatically convert any input to uppercase.

To test the functionality, an ElevatedButton is added that retrieves the value entered in the TextFormField when clicked.
This showcases that the input in the TextFormField is indeed automatically converted to uppercase.

Leave a comment