24 lines
848 B
Dart
24 lines
848 B
Dart
import 'package:flutter/services.dart';
|
|
|
|
/// 金额输入过滤:仅数字 + 单小数点 + 最多 2 位小数
|
|
///
|
|
/// [allowNegative] 为 true 时允许开头的负号(账户余额可能为负)。
|
|
/// 记账金额、预算不使用负号,保持默认 false。
|
|
class AmountInputFormatter extends TextInputFormatter {
|
|
AmountInputFormatter({this.allowNegative = false});
|
|
|
|
final bool allowNegative;
|
|
|
|
static final _positiveRegex = RegExp(r'^\d*\.?\d{0,2}$');
|
|
static final _negativeRegex = RegExp(r'^-?\d*\.?\d{0,2}$');
|
|
|
|
@override
|
|
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
|
|
final text = newValue.text;
|
|
if (text.isEmpty) return newValue;
|
|
final regex = allowNegative ? _negativeRegex : _positiveRegex;
|
|
if (!regex.hasMatch(text)) return oldValue;
|
|
return newValue;
|
|
}
|
|
}
|