본문 바로가기
프로그래밍/Flutter <Dart>

[Flutter] Flutter에서 "000-0000-0000" 형식으로 자동 하이픈(-) 추가되는 TextFormField 만들기

by TaeGyeong Lee 2024. 8. 19.

개요 

플러터 앱에서 전화번호 입력 시 하이픈이 자동으로 추가되는 Formatter를 적용해 보겠습니다. 

 

Formatter 생성 

class HyphenFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    if (newValue.text.length > 12) {
      return oldValue;
    }
    
    final newText = StringBuffer();
    for (int i = 0; i < newValue.text.length; i++) {
      if (i == 3 || i == 7) {
        newText.write('-');
      }
      newText.write(newValue.text[i]);
    }
    
    return TextEditingValue(
      text: newText.toString(),
      selection: TextSelection.collapsed(offset: newText.length),
    );
  }
}

 

Controller 선언 

final TextEditingController _controller = TextEditingController();

 

TextFormField 에 적용 

반드시 FilteringTextInputFormatter.digitsOnly을 inputFormatter에 추가해 주세요. 

TextFormField(
  controller: _controller,
  keyboardType: TextInputType.number,
  inputFormatters: [
    FilteringTextInputFormatter.digitsOnly,
    HyphenFormatter(),
  ],
  decoration: InputDecoration(
    hintText: '000-0000-0000',
    border: OutlineInputBorder(),
  ),
)

 

참고 자료 

 

TextFormField class - material library - Dart API

A FormField that contains a TextField. This is a convenience widget that wraps a TextField widget in a FormField. A Form ancestor is not required. The Form allows one to save, reset, or validate multiple fields at once. To use without a Form, pass a Global

api.flutter.dev

 

Insert Dash in TextFormField

I have a TextFormField where the user should enter a string in the following format: XX-XX-XX Is there anyway to automatically add the "-" as the user is typing? Thanks

stackoverflow.com