Flutter中如何实现带预设格式的日期输入TextFormField组件?
Flutter 带固定格式的日期输入实现方案
完全可以实现这种带固定格式的日期输入,不管是用现成组件还是自定义配置都不算复杂:
一、现成组件推荐
直接用mask_text_input_formatter这个包就能快速搞定,它专门处理带掩码的输入场景,刚好匹配你的需求。
用法示例:
import 'package:flutter/material.dart'; import 'package:mask_text_input_formatter/mask_text_input_formatter.dart'; class DateInputField extends StatelessWidget { final dateMaskFormatter = MaskTextInputFormatter( mask: '##/##/####', filter: {"#": RegExp(r'[0-9]')}, type: MaskAutoCompletionType.lazy, ); @override Widget build(BuildContext context) { return TextFormField( keyboardType: TextInputType.number, inputFormatters: [dateMaskFormatter], decoration: const InputDecoration( hintText: '__/__/____', labelText: '输入日期', ), ); } }
这个组件会自动处理输入逻辑:输入05时显示05/__/____,连续输入01012023会自动转为01/01/2023,用户只能在#对应的位置输入数字,完全符合你的要求。
二、自定义实现(无需第三方包)
如果不想依赖外部包,也可以自己写一个TextInputFormatter来实现:
class DateInputFormatter extends TextInputFormatter { @override TextEditingValue formatEditUpdate( TextEditingValue oldValue, TextEditingValue newValue, ) { // 过滤掉非数字字符 final newText = newValue.text.replaceAll(RegExp(r'[^0-9]'), ''); String formattedText = ''; // 按格式拼接字符 if (newText.length >= 2) { formattedText += '${newText.substring(0, 2)}/'; if (newText.length >= 4) { formattedText += '${newText.substring(2, 4)}/'; formattedText += newText.length >= 8 ? newText.substring(4, 8) : newText.substring(4); } else { formattedText += newText.substring(2); } } else { formattedText = newText; } return TextEditingValue( text: formattedText, selection: TextSelection.collapsed(offset: formattedText.length), ); } }
然后在TextFormField中使用这个自定义 formatter:
TextFormField( keyboardType: TextInputType.number, inputFormatters: [DateInputFormatter()], decoration: const InputDecoration( hintText: '__/__/____', labelText: '输入日期', ), )
这种方式也能实现完全一致的效果,且无需引入额外依赖。
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

