Mark Codd
Mark Codd

Reputation: 3

Flutter FormatException

I am trying to have a controller for a TextFormField show decimal numbers from the text input. here is my code:

void initState() {
    super.initState();
    _controller.addListener(() {
      final text = _controller.text;
      final amount = int.parse(text);
      final showAmount = (amount/100).toStringAsFixed(2);
      _controller.value = _controller.value.copyWith(
          text: showAmount,
          selection: TextSelection(
            baseOffset: showAmount.length,
            extentOffset: showAmount.length,
          ),
          composing: TextRange.empty
      );
    });
  }

It works, however in the console I keep getting the following exception: The following FormatException was thrown while dispatching notifications for TextEditingController: Invalid radix-10 number (at character 1)

Is there a better way to parse into an int or show a string with decimal numbers?

Upvotes: 0

Views: 1391

Answers (1)

dev-aentgs
dev-aentgs

Reputation: 1288

Tried to provide the below changes in this small code sample pastebin,

  1. Added a separate readOnly TextField for the output.
  2. Restricted the input TextField to intgers only using keyboardType: TextInputType.number, and inputFormatters: [WhitelistingTextInputFormatter.digitsOnly].
  3. Added checks for isEmpty and initial value is set to blank String.

Hope this helps.

Upvotes: 1

Related Questions