Skip to content

Instantly share code, notes, and snippets.

@yamatatsu10969
Last active September 14, 2021 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yamatatsu10969/97c3327c9dfe0d527cc35cd3c560f203 to your computer and use it in GitHub Desktop.
Save yamatatsu10969/97c3327c9dfe0d527cc35cd3c560f203 to your computer and use it in GitHub Desktop.
Custom TextInputFormatter Auto Fill Hyphen [Flutter]
class JapanesePhoneNumberFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
final oldValueLength = oldValue.text.length;
final newValueLength = newValue.text.length;
final isStartZero = newValue.text.startsWith('0');
if (newValueLength > 0 && newValueLength > oldValueLength) {
final maxLengthIncludeHyphen = isStartZero ? 13 : 12;
if (newValueLength > maxLengthIncludeHyphen) {
return oldValue;
}
if (newValueLength == (isStartZero ? 3 : 2)) {
return newValue.copyWith(
text: newValue.text + '-',
selection: TextSelection.collapsed(offset: (isStartZero ? 4 : 3)),
);
}
if (newValueLength == (isStartZero ? 8 : 7)) {
return newValue.copyWith(
text: newValue.text + '-',
selection: TextSelection.collapsed(offset: (isStartZero ? 10 : 9)),
);
}
}
return newValue;
}
}
@yamatatsu10969
Copy link
Author

yamatatsu10969 commented Sep 14, 2021

勝手にハイフンが入るフォーマッター

使い方

           TextFormField(
              onChanged: (value) {
              },
              inputFormatters: [
                // FilteringTextInputFormatter.digitsOnly,
                JapanesePhoneNumberFormatter(),
              ],
              /// 電話番号のmaxは15桁のため
              maxLength: 15,
            )
CleanShot.2021-09-14.at.16.44.42.mp4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment