flutterdarttextfieldtextformfieldstatelesswidget

Flutter: How to call a function before onChanged Method from TextFormField gets called?


I have a reusable TextFormField Widget for decimal number inputs. If the user input a decimal number with a comma instead of a dot I want to replace it. So for that I created a reusable TextFormField Widget where I want to replace the comma with a dot before the onChanged method. But how can I call the function replaceCommaWithDot() before onChanged gets called? This is the reusable Widget:

class DecimalTextFormField extends StatelessWidget {
  const DecimalTextFormField({Key? key, this.onChanged})
      : super(key: key);
  final ValueChanged? onChanged;

  @override
  Widget build(BuildContext context) {

    replaceCommaWithDot(String inputNumber) {
      if (inputNumber.contains(',')) {
        String newText = inputNumber.replaceAll(',', '.');
        return newText;
      }
      return inputNumber;
    }

    return TextFormField(
      keyboardType: const TextInputType.numberWithOptions(decimal: true),
      // how to use replaceCommaWithDot method when onChanged gets called?
      onChanged: onChanged,
    );
  }
}

Solution

  • Your snippet will work fine if you just want result(without ui update).

      onChanged: (value) {
            final v = replaceCommaWithDot(value);
            if (onChanged != null) onChanged!(v);
          },
    

    If you also wish to update the UI, you can use inputFormatters

    
    class CustomFormater extends TextInputFormatter {
      replaceCommaWithDot(String inputNumber) {
        if (inputNumber.contains(',')) {
          String newText = inputNumber.replaceAll(',', '.');
          return newText;
        }
        return inputNumber;
      }
    
      @override
      TextEditingValue formatEditUpdate(
          TextEditingValue oldValue, TextEditingValue newValue) {
        return newValue.copyWith(text: replaceCommaWithDot(newValue.text));
      }
    }
    

    And DecimalTextFormField will return

    return TextFormField(
      keyboardType: const TextInputType.numberWithOptions(decimal: true),
      // how to use replaceCommaWithDot method when onChanged gets called?
      inputFormatters: [
        CustomFormater(),
      ],
      onChanged: (value) {
        if (onChanged != null) onChanged!(value);
      },
    );
    

    More about TextInputFormatter.