Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way for InputFormatters on a TextFormField to be executed when the form is initially displayed?

Tags:

flutter

When inputFormatters are specified on a TextFormField, the initialValue is not processed by the inputFormatters.

This seems odd. Is there a recommended way to get the inputFormatters to format the initialValue.

For example, I have a 5 digit number (i.e. 12345) that should be displayed with a comma separator (12,345) in the input field. By default it displays as 12345, but as soon as I edit the value, the comma separator appears. The comma separator should be displayed on the initial value.

like image 892
Simpler Avatar asked Dec 28 '18 15:12

Simpler


1 Answers

You can create a static method to validate your initialValue

class MyFormater extends TextInputFormatter {
  static String defaultFormat(String text) {
    // Do whatever you want
    return text;
  }

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    // Your validations/formats
    return null;
  }
}

and then you can use it as so

TextFormField(
            initialValue: MyFormater.defaultFormat(someString),
            inputFormatters: [MyFormater()],
          )

I doubt there is other way that will trigger the TextInputFormatter before it has any focus. That initialValue is mean to be already validated and work as a placeholder.

like image 51
Miguel Ruivo Avatar answered Nov 15 '22 18:11

Miguel Ruivo