Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CurrencyInputFormatter - Incorrect cursor position when typing 0 with a leading symbol #134

Open
nizioleque opened this issue Jul 8, 2023 · 1 comment

Comments

@nizioleque
Copy link

I am using the CurrencyInputFormatter with a leading symbol (let's say EUR).

When I enter a non-zero digit the cursor is positioned correctly next to the period (which is correct an expected behavior) - example: in an empty field I input 1. The result is EUR1|.00 where | is the cursor position.

But when I enter 0, the cursor is not positioned correctly - example: in an empty field I input 0. The result is E|UR0.00.

I would appreciate a fix for this issue :)

@nizioleque
Copy link
Author

nizioleque commented Jul 8, 2023

Here is my temporary walkaround for this issue:

I add two formatters before and after the CurrencyInputFormatter - the first one detects this issue, changes the 0 to a 1, then CurrencyInputFormatter sets the cursor position correctly, then the second one changes the 1 back to a 0. A List is used to pass the boolean by reference.

In the widget:

List<bool> shouldReplace = [false];

// ...

TextFormField(
  inputFormatters: [
    FixZeroBeforeInputFormatter(shouldReplace),
    CurrencyInputFormatter(leadingSymbol: 'EUR'),
    FixZeroAfterInputFormatter(shouldReplace)
  ],
)

and here are the formatters:

class FixZeroBeforeInputFormatter extends TextInputFormatter {
  FixZeroBeforeInputFormatter(this.shouldReplace);

  List<bool> shouldReplace;

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    if (newValue.text == '0') {
      shouldReplace[0] = true;
      return newValue.copyWith(text: '1');
    }

    return newValue;
  }
}

class FixZeroAfterInputFormatter extends TextInputFormatter {
  FixZeroAfterInputFormatter(this.shouldReplace);

  List<bool> shouldReplace;

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    bool tmpShouldReplace = shouldReplace[0];
    shouldReplace[0] = false;

    if (tmpShouldReplace) {
      String newText = newValue.text.replaceFirst('1', '0');
      return newValue.copyWith(text: newText);
    }

    return newValue;
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant