颤振中的千位分隔符

Thousand separator in flutter

在 flutter 的 TextFormField 中输入数字时,有没有办法制作千位分隔符? 这是我的 TextFormField

child: TextFormField(
 decoration: InputDecoration(
     border: const OutlineInputBorder()),
 keyboardType: TextInputType.number,
),

先添加intlflutter包

dependencies:
  intl: ^0.16.1

现在使用NumberFormat

 var formatter = new NumberFormat("#,###");
  print(formatter.format(1234)), // this will be: 1,234

Flutter 中没有内置任何东西来处理这个问题。您将不得不使用自己的自定义文本格式化程序。 (源自 this answer。)

import 'package:flutter/services.dart';

class ThousandsSeparatorInputFormatter 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;
  }
}

用法:

TextField(
  decoration: InputDecoration(
    border: const OutlineInputBorder(),
  ),
  keyboardType: TextInputType.number,
  inputFormatters: [ThousandsSeparatorInputFormatter()],
),

示例:https://codepen.io/Abion47/pen/mdVLgGP