gpt4 book ai didi

flutter - flutter 中的千位分隔符

转载 作者:行者123 更新时间:2023-12-03 04:43:02 24 4
gpt4 key购买 nike

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

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

最佳答案

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

关于flutter - flutter 中的千位分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62821439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com