공부방/Flutter

Flutter TextFormField 폰 번호 양식 자동 완성 코드

soycrab 2023. 7. 4. 17:50

핸드폰 번호를 입력하면 자동으로 '-'를 입력해 주는 TextField Formatter를 만들어 보려구 해요. 

회원가입이나 여러가지 이벤트 페이지 정보 작성 시 핸드폰 번호를 입력할 일이 있으면 쉽게 사용 가능해요. 

물론 라이브러리를 사용해도 되긴 하지만 이정도는 그냥 코드로 만들어보아요.

아래코드로 얼마든지 다른 형식도 응용이 가능하니 유용하게 사용해 주세요. 

PhoneNumberTextInputFormatter.dart

import 'package:flutter/services.dart';

class PhoneNumberTextInputFormatter extends TextInputFormatter {

  ///전체 번호 010-1234-5678 기준
  final firstLength = 3; ///첫번째 번호 갯수 ex) 010  3개
  final secondLength = 4; ///두번째 번호 갯수 ex) 1234 4개
  final thirdLength = 4; ///세번째 번호 갯수 ex) 5678  4개

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    final int newTextLength = newValue.text.length;
    int usedSubstringIndex = 0;
    final StringBuffer newText = StringBuffer();
    if (newTextLength >= firstLength + 1) {
      newText.write('${newValue.text.substring(0, usedSubstringIndex = firstLength)}-');
    }
    if (newTextLength >= firstLength + secondLength + 1) {
      newText.write('${newValue.text.substring(firstLength, usedSubstringIndex = firstLength + secondLength)}-');
    }
    if (newTextLength >= firstLength + secondLength + thirdLength + 1) {
      newText.write(newValue.text.substring(firstLength + secondLength, usedSubstringIndex = firstLength + secondLength + thirdLength) );
    }
    if (newTextLength >= usedSubstringIndex) {
      newText.write(newValue.text.substring(usedSubstringIndex));
    }
    return TextEditingValue(
      text: newText.toString(),
      selection: TextSelection.collapsed(offset: newText.length),
    );
  }
}

 

사용 방법 

TextFormField(
      ....
    
                keyboardType: TextInputType.phone,
                inputFormatters : [
                  FilteringTextInputFormatter.allow(RegExp("[0-9/]")),
                  PhoneNumberTextInputFormatter(),
                ],)

 

반응형