Тысячный разделитель во флейте - PullRequest
0 голосов
/ 09 июля 2020

Есть ли способ сделать разделитель тысяч при вводе чисел в TextFormField во флаттере? Это мой TextFormField

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

Ответы [ 2 ]

1 голос
/ 09 июля 2020

Во 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

0 голосов
/ 09 июля 2020

Первое добавление intl flutter package

dependencies:
  intl: ^0.16.1

Теперь используйте NumberFormat

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