这对我有用(2022 年 2 月)
将文本限制为 2 个小数点,并且只有 1 个 '.' (句号)
如果用户手动删除 '.' 之前的数字,0 将自动添加到数字的开头。
PS:对答案稍作修改
TextFormField
TextFormField(
autofocus: false,
keyboardType: TextInputType.number,
controller: controller,
inputFormatters: [
DecimalTextInputFormatter(decimalRange: 2),
],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please add amount.';
}
return null;
},
DecimalTextInputFormatter
import 'package:flutter/services.dart';
import 'dart:math' as math;
class DecimalTextInputFormatter extends TextInputFormatter {
DecimalTextInputFormatter({required this.decimalRange})
: assert(decimalRange > 0);
final int decimalRange;
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
TextSelection newSelection = newValue.selection;
String truncated = newValue.text;
String value = newValue.text;
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),
);
} else if (value.contains(".")) {
String tempValue = value.substring(value.indexOf(".") + 1);
if (tempValue.contains(".")) {
truncated = oldValue.text;
newSelection = oldValue.selection;
}
if (value.indexOf(".") == 0) {
truncated = "0" + truncated;
newSelection = newValue.selection.copyWith(
baseOffset: math.min(truncated.length, truncated.length + 1),
extentOffset: math.min(truncated.length, truncated.length + 1),
);
}
}
if (value.contains(" ") || value.contains("-")) {
truncated = oldValue.text;
newSelection = oldValue.selection;
}
return TextEditingValue(
text: truncated,
selection: newSelection,
composing: TextRange.empty,
);
}
}