Flutter学习笔记(42)--限定TextField输入内容,仅允许数字和小数点后两位
import 'package:flutter/services.dart'; import 'dart:math' as math; class InputFormat extends TextInputFormatter { InputFormat({this.decimalRange = 2}) : assert(decimalRange == null || decimalRange > 0); final int decimalRange; @override TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { // 拿到录入后的字符 String nValue = newValue.text; //当前所选择的文字区域 TextSelection nSelection = newValue.selection; // 先来一波过滤,过滤出数字及小数点 // 匹配包含数字和小数点的字符 Pattern p = RegExp(r'(\d+\.?)|(\.?\d+)|(\.?)'); nValue = p.allMatches(nValue) .map<String>((Match match) => match.group(0)) .join(); // 用匹配完的字符判断 if (nValue.startsWith('.')) { //如果小数点开头,我们给他补个0 nValue = '0.'; } else if (nValue.contains('.')) { //来验证小数点位置 if (nValue.substring(nValue.indexOf('.') + 1).length > decimalRange) { nValue = oldValue.text; } else { if (nValue.split('.').length > 2) { //多个小数点,去掉后面的 List<String> split = nValue.split('.'); nValue = split[0] + '.' + split[1]; } } } //使光标定位到最后一个字符后面 nSelection = newValue.selection.copyWith( baseOffset: math.min(nValue.length, nValue.length + 1), extentOffset: math.min(nValue.length, nValue.length + 1), ); return TextEditingValue( text: nValue, selection: nSelection, composing: TextRange.empty ); } }
使用:
keyboardType: TextInputType.numberWithOptions(decimal: true), inputFormatters: [InputFormat()],
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】