如果需要自定义格式化输入,需要手动集成TextInputFormatter来实现,需要留意文本格式和光标位置。官方只提供了三个formatters

    1. WhitelistingTextInputFormatter 白名单校验,也就是只允许输入符合规则的字符
    2. BlacklistingTextInputFormatter 黑名单校验,除了规定的字符其他的都可以输入
    3. LengthLimitingTextInputFormatter 长度限制,跟maxLength作用类似 ```dart TextField( autofocus: true, keyboardType: TextInputType.phone, decoration: InputDecoration(hintText: “输入手机号码”, counterText: ‘’, hintStyle: TextStyle(color: HexColor(“#DBDBDB”), fontSize: 15), border: InputBorder.none), cursorColor: HexColor(“#222222”), cursorWidth: 0.3, style: TextStyle(color: HexColor(“#161616”), fontWeight: FontWeight.bold, fontSize: 28), textAlign: TextAlign.center, maxLength: 13, maxLengthEnforced: true, /// 官方只提供了三个formatter 有额外的需求需要自己定义formatter inputFormatters: [WhitelistingTextInputFormatter(RegExp(“[0-9]”)), _UsNumberTextInputFormatter()], controller: _phoneNumberController, ),

    /// 格式化输入手机号为 -> ### #### #### class _UsNumberTextInputFormatter extends TextInputFormatter { @override TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { final int newTextLength = newValue.text.length; int selectionIndex = newValue.selection.end; // 光标位置 int usedSubstringIndex = 0; final StringBuffer newText = StringBuffer(); if (newTextLength >= 4) { newText.write(newValue.text.substring(0, usedSubstringIndex = 3) + ‘ ‘); if (newValue.selection.end >= 3) selectionIndex++; } if (newTextLength >= 8) { newText.write(newValue.text.substring(3, usedSubstringIndex = 7) + ‘ ‘); if (newValue.selection.end >= 7) selectionIndex++; } // Dump the rest. if (newTextLength >= usedSubstringIndex) newText.write(newValue.text.substring(usedSubstringIndex)); return TextEditingValue( text: newText.toString(), selection: TextSelection.collapsed(offset: selectionIndex), ); } } ```