Last active
September 14, 2021 08:36
-
-
Save yamatatsu10969/97c3327c9dfe0d527cc35cd3c560f203 to your computer and use it in GitHub Desktop.
Custom TextInputFormatter Auto Fill Hyphen [Flutter]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
勝手にハイフンが入るフォーマッター
使い方
CleanShot.2021-09-14.at.16.44.42.mp4