2

I'm trying to parse input in Flutter and extract Double value there. I.e. user can only input decimal numbers.

To do this I'm using TextField:

TextField(
                    keyboardType: TextInputType.numberWithOptions(signed: false, decimal: true)
                    controller: _controller,
                  )

However on iOS device I have keyboard with numbers and comma(,), not dot (.). When user inputs comma I'm parsing string and having error like this:

Error: FormatException: Invalid double 5,

What is the best way to handle this? Some dirty solutions are:

  • use TextInputType.numberWithOptions(signed: true, decimal: true) - this gives keyboard with not only numbers and user input dot there.
  • maybe somehow replace commas with dots first

2 Answers2

2

In order to replace comma with dot when user is typing before onChanged callback (or validator) use inputFormatters

  1. Create a new TextFormatter
class ReplaceCommaFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    return TextEditingValue(
      text: newValue.text.replaceAll(',', '.'),
      selection: newValue.selection,
    );
  }
}
  1. Use the new TextFormatter in the TextField
TextFormField(
  keyboardType: TextInputType.numberWithOptions(decimal: true),
  inputFormatters: [
    ReplaceCommaFormatter(),
  ],
  onChanged: ((String? val) {
    // now to double will work correctly
  }),
)
Nelu B
  • 257
  • 2
  • 10
-1

The reason behind showing of the comma is because of the device's local region formats. Maybe this link can help you out.

Sagun Raj Lage
  • 2,326
  • 2
  • 18
  • 28