'Flutter TextField value always uppercase & debounce

I am new in Flutter. I am looking for TextField value to always uppercase but I did not find any resource on that.

Another issue is the TextField onChanged event debounce implementation. When I type on TextField it immediately fires onChanged event which is not suitable for my goal. The onChange event will fire after 500ms on every text changed.

 new TextField(
         controller: _controller,
         decoration: new InputDecoration(
              hintText: 'Search here',
         ),
         onChanged: (str) {
            //need to implement debounce
         }
)


Solution 1:[1]

Works on Android, iOS, Web, macOS, Windows and Linux

You can implement a custom TextInputFormatter

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

Usage:

TextField(
  inputFormatters: [
    UpperCaseTextFormatter(),
  ]
)

Full example

Solution 2:[2]

Perhaps using textCapitalization: TextCapitalization.characters in the TextField could help you? Although this would capitalize the characters while something is being typed as well.

TextField(
    textCapitalization: TextCapitalization.sentences,
)

Solution 3:[3]

You can use textCapitalization property of a TextField widget. Also do take a reference for detailed API info here Text Capitalization Official API

Illustration as follow

Example 1

 TextField(
        initialValue: flutter code camp
        textCapitalization: TextCapitalization.characters,
    )// OUTPUT : FLUTTER CODE CAMP

Example 2

 TextField(
        initialValue: flutter code camp
        textCapitalization: TextCapitalization.words,
    )// OUTPUT : Flutter Code Camp

Example 3

 TextField(
        initialValue: flutter code camp
        textCapitalization: TextCapitalization.sentences,
    )// OUTPUT : Flutter code camp

Example 4

 TextField(
        initialValue: flutter code camp
        textCapitalization: TextCapitalization.none,
    )// OUTPUT : flutter code camp

Solution 4:[4]

Everything you need to do is:

After String put .toUpperCase()

Example: "Some text".toUpperCase()

This worked in my case. I am new too, so I hope I helped.

Solution 5:[5]

You can use TextCapitalization.characters to make all typed characters UPPERCASE

TextField(
    textCapitalization: TextCapitalization.characters,
)

Solution 6:[6]

The easiest way to do it is to add the onChanged event of the TextField and convert to uppercase using the controller of the TextField just like the above:

TextField(
          controller: controllerReservation,
          onChanged: (value) {               
            controllerReservation.value = 
               TextEditingValue(
                                text: value.toUpperCase(), 
                                selection: controllerReservation.selection);
          },
        )

Solution 7:[7]

TextField has a textCapitalization property that you can use to capitalize words Sentences or characters

if you want to capitalize the entire value of your text input use

TextField(
  textCapitalization: TextCapitalization.characters,
 )

Solution 8:[8]

To do Uppercase

You have to use textCapitalization: TextCapitalization.characters to enter always uppercase

textCapitalization: TextField provides options for capitalizing the text entered by the user.

Use TextCapitalization.characters: Capitalize all characters in the sentence.

TextField(
 textCapitalization: TextCapitalization.characters,
),

To do Debounce

We can easily debounce the input stream. Create a Debouncer class using Timer

import 'package:flutter/foundation.dart';
import 'dart:async';

class Debouncer {
  final int milliseconds;
  VoidCallback action;
  Timer _timer;

  Debouncer({ this.milliseconds });

  run(VoidCallback action) {
    if (_timer != null) {
      _timer.cancel();
    }

    _timer = Timer(Duration(milliseconds: milliseconds), action);
  }
}

Declare and trigger

final _debouncer = Debouncer(milliseconds: 500);

onTextChange(String text) {
  _debouncer.run(() => print(text));
}

Debounce alleviates pressure on the server by putting all input events "on hold" for a given duration.

We can control the debounce duration to our liking (500ms is a good default value).

Solution 9:[9]

@Günter-Zöchbauer's solution works but when you switch into the numeric keyboard on Android, if you type one, it'll switch into the letters keyboard again.

This is because you're setting a new TextEditingValue every time.

Instead, if you copy the newest one and change the text, it works:

import 'package:flutter/services.dart';

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

Solution 10:[10]

Here is how you achieve Debounce (or delay) effect on input text:

1) Import package

rxdart: ^0.18.1 (or whatever the version will be)

2) In your Stateful Widget declare following

final subject = new PublishSubject<String>();

3) In the same Stateful Widget, declare the following under initState method

subject.stream
    .debounce(new Duration(milliseconds: 500))
    .listen(_loadNewData);

4) In the same Stateful Widget, create the following method (that will be fired after 500 ms)

  void _loadNewData(String newData) {
    //do update here
  }

4) Add the following line to your Textfield Widget (you can get rid of Controller now)

onChanged: (string) => (subject.add(string)),

Solution 11:[11]

Here's simple approach to type in CAPS ON

 textCapitalization: TextCapitalization.characters,

Easy!

Solution 12:[12]

TextField(
  controller: textController,
    onChanged: (value) {
      if (textController.text != value.toUpperCase())
        textController.value = textController.value.copyWith(text: value.toUpperCase());
  },
)

Solution 13:[13]

Here is a util class that can help with it:

 class TextCapitalizationFormatter extends TextInputFormatter {
      final TextCapitalization capitalization;

  TextCapitalizationFormatter(this.capitalization);

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    String text = '';

    switch (capitalization) {
      case TextCapitalization.words:
        text = capitalizeFirstofEach(newValue.text);
        break;
      case TextCapitalization.sentences:
        List<String> sentences = newValue.text.split('.');
        for (int i = 0; i < sentences.length; i++) {
          sentences[i] = inCaps(sentences[i]);
          print(sentences[i]);
        }
        text = sentences.join('.');
        break;
      case TextCapitalization.characters:
        text = allInCaps(newValue.text);
        break;
      case TextCapitalization.none:
        text = newValue.text;
        break;
    }

    return TextEditingValue(
      text: text,
      selection: newValue.selection,
    );
  }

  /// 'Hello world'
  static String inCaps(String text) {
    if (text.isEmpty) {
      return text;
    }
    String result = '';
    for (int i = 0; i < text.length; i++) {
      if (text[i] != ' ') {
        result += '${text[i].toUpperCase()}${text.substring(i + 1)}';
        break;
      } else {
        result += text[i];
      }
    }
    return result;
  }

  /// 'HELLO WORLD'
  static String allInCaps(String text) => text.toUpperCase();

  /// 'Hello World'
  static String capitalizeFirstofEach(String text) => text
      .replaceAll(RegExp(' +'), ' ')
      .split(" ")
      .map((str) => inCaps(str))
      .join(" ");
}

Usage:

TextField(
  inputFormatters: [
    TextCapitalizationFormatter(TextCapitalization.sentences),
  ]
)