如何在 Flutter 中使用格式化程序格式化 TextFormField 的初始值?

Pav*_*l_K 1 dart flutter

我有一个文本字段,用户可以在其中输入总和。我希望这些总和按数千进行格式化(例如500 000)。我找到了一个可以做到这一点的格式化程序。问题是,当在控制器中设置初始值时,不会调用此格式化程序。因此,在用户修改文本之前,文本不会被格式化。

例如,如果我们将初始值设置为500000文本字段显示的内容,500000而不是 500 000直到用户修改该值为止。

这是我的代码:

class ThousandTextInputFormatter extends TextInputFormatter {
  static const separator = ','; // Change this to '.' for other locales

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    // Short-circuit if the new value is empty
    if (newValue.text.length == 0) {
      return newValue.copyWith(text: '');
    }

    // Handle "deletion" of separator character
    String oldValueText = oldValue.text.replaceAll(separator, '');
    String newValueText = newValue.text.replaceAll(separator, '');

    if (oldValue.text.endsWith(separator) &&
        oldValue.text.length == newValue.text.length + 1) {
      newValueText = newValueText.substring(0, newValueText.length - 1);
    }

    // Only process if the old value and new value are different
    if (oldValueText != newValueText) {
      int selectionIndex =
          newValue.text.length - newValue.selection.extentOffset;
      final chars = newValueText.split('');

      String newString = '';
      for (int i = chars.length - 1; i >= 0; i--) {
        if ((chars.length - 1 - i) % 3 == 0 && i != chars.length - 1)
          newString = separator + newString;
        newString = chars[i] + newString;
      }

      return TextEditingValue(
        text: newString.toString(),
        selection: TextSelection.collapsed(
          offset: newString.length - selectionIndex,
        ),
      );
    }

    // If the new value and old value are the same, just return as-is
    return newValue;
  }
}

...

var sumController = TextEditingController(text: 500000.toString());//setting initial value
...
TextFormField(
  inputFormatters: [ThousandTextInputFormatter()],
  controller: sumController,
)
Run Code Online (Sandbox Code Playgroud)

如果可能的话,有人能说一下如何使用格式化程序格式化初始值吗?

Pav*_*l_K 6

我让它这样工作:

sumController.value = ThousandTextInputFormatter()    
  .formatEditUpdate(TextEditingValue.empty, TextEditingValue(text: 500000.toString()));
Run Code Online (Sandbox Code Playgroud)