【发布时间】:2021-02-14 18:53:26
【问题描述】:
我对 Flutter InputTextField 有疑问。我正在开发一个像 CashApp 这样的应用程序,如果你有一个可以向其他人汇款的功能。
问题是:我需要实现一个数字格式并且只允许两位小数。
例如,如果我输入:
-
"1000,25" -> 需要转换为 1.000,25
-
"10000,25" -> 需要转换为 10.000,25
等等..
我一直在使用此代码来达到唯一的两位小数部分
import 'package:flutter/services.dart';
import 'dart:math' as math;
class DecimalTextInputFormatter extends TextInputFormatter {
DecimalTextInputFormatter({this.decimalRange, this.activatedNegativeValues})
: assert(decimalRange == null || decimalRange >= 0,
'DecimalTextInputFormatter declaretion error');
final int decimalRange;
final bool activatedNegativeValues;
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, // unused.
TextEditingValue newValue,
) {
TextSelection newSelection = newValue.selection;
String truncated = newValue.text;
if (newValue.text.contains(' ')) {
return oldValue;
}
if (newValue.text.isEmpty) {
return newValue;
} else if (double.tryParse(newValue.text) == null &&
!(newValue.text.length == 1 &&
(activatedNegativeValues == true ||
activatedNegativeValues == null) &&
newValue.text == '-')) {
return oldValue;
}
if (activatedNegativeValues == false &&
double.tryParse(newValue.text) < 0) {
return oldValue;
}
if (decimalRange != null) {
String value = newValue.text;
if (decimalRange == 0 && value.contains(".")) {
truncated = oldValue.text;
newSelection = oldValue.selection;
}
if (value.contains(".") &&
value.substring(value.indexOf(".") + 1).length > decimalRange) {
truncated = oldValue.text;
newSelection = oldValue.selection;
} else if (value == ".") {
truncated = "0.";
newSelection = newValue.selection.copyWith(
baseOffset: math.min(truncated.length, truncated.length + 1),
extentOffset: math.min(truncated.length, truncated.length + 1),
);
}
return TextEditingValue(
text: truncated,
selection: newSelection,
composing: TextRange.empty,
);
}
return newValue;
}
}
这是我从post找到的回复
这段代码几乎可以做到这一点。它限制了两位小数部分,但没有 NumberFormat 部分,并且小数部分不使用“逗号”,而是使用“点”。
我想交换 '.'千位,',' 代表小数。并添加 NumberFormat。
有什么方法可以实现吗?
【问题讨论】:
标签: flutter validation dart decimal textinput