Flutter中FilteringTextInputFormatter.allow限制TextField输入连续点的异常问题
I've run into this exact quirk on iOS before—it's definitely confusing when your allowed characters seem to get swallowed up unexpectedly!
The root cause here is iOS's built-in smart punctuation feature: when you type three consecutive dots quickly, iOS automatically replaces them with a single ellipsis character (…). Since this ellipsis isn't included in your regex [a-zA-Z0-9@,#.], the FilteringTextInputFormatter.allow filters it out entirely, leaving no trace of the three dots you typed.
Here are a couple of straightforward fixes to resolve this:
Fix 1: Disable Smart Punctuation (Recommended)
Flutter added a smartPunctuationEnabled property in version 3.3.0 that lets you turn off iOS's automatic punctuation replacement. Just add this line to your TextFormField:
TextFormField( autocorrect: false, enableSuggestions: false, smartPunctuationEnabled: false, // Add this to block auto-ellipsis inputFormatters: [ FilteringTextInputFormatter.allow(RegExp("[a-zA-Z0-9@,#.]")), LengthLimitingTextInputFormatter(20), ], )
This prevents iOS from replacing your three dots with an ellipsis in the first place, so the formatter will keep all the dots you type exactly as entered.
Fix 2: Allow Ellipsis in Regex (Alternative)
If you don't mind the ellipsis character appearing instead of three separate dots, you can update your regex to include it:
FilteringTextInputFormatter.allow(RegExp("[a-zA-Z0-9@,#.…]")), // Added ellipsis to allowed set
This way, when iOS replaces the three dots with an ellipsis, it's allowed and won't be filtered out. Note that this will display a single ellipsis symbol rather than three individual dots.
Fix 3: Custom Formatter to Convert Ellipsis Back to Three Dots
If you want to keep smart punctuation for other cases but still show three dots instead of an ellipsis, add a custom formatter to convert any auto-generated ellipsis back to three dots:
TextFormField( autocorrect: false, enableSuggestions: false, inputFormatters: [ FilteringTextInputFormatter.allow(RegExp("[a-zA-Z0-9@,#.…]")), LengthLimitingTextInputFormatter(20), // Custom formatter to swap ellipsis for three dots TextInputFormatter.withFunction((oldValue, newValue) { return TextEditingValue( text: newValue.text.replaceAll('…', '...'), selection: newValue.selection, composing: newValue.composing, ); }), ], )
This lets iOS do its replacement, then converts the ellipsis back to three dots before displaying it to the user.
I'd recommend Fix 1 since it directly addresses the source of the issue and gives you the exact input you expect. Just make sure you're using Flutter 3.3.0 or later to access the smartPunctuationEnabled property.
备注:内容来源于stack exchange,提问作者Shebin Koshy

