0

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

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

2 回答 2

1

首先添加国际颤振包

dependencies:
  intl: ^0.16.1

现在使用NumberFormat

 var formatter = new NumberFormat("#,###");
  print(formatter.format(1234)), // this will be: 1,234
于 2020-07-09T18:35:52.203 回答
1

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

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

于 2020-07-09T19:17:55.320 回答