본문 바로가기
귀펀치토끼는 부서지지 않는다.
주소(D)
카테고리 없음

[Flutter] 전화번호 입력시 자동 하이픈

// 클래스 안에

TextField(
    // onChanged: controller.registerPhone,
    onChanged: (value) {
      String formattedNumber = formatPhoneNumber(value);
      controller.registerPhone(formattedNumber);
    },
    keyboardType: TextInputType.phone,
    inputFormatters: [
    	PhoneNumberFormatter(), 
        LengthLimitingTextInputFormatter(13)
      ],
    decoration: InputDecoration(
      hintText: '010-4567-2345',
      hintStyle: TextStyle(
        color: const Color(0xFF979797),
        fontSize: 14.sp,
        fontWeight: FontWeight.w400,
      ),
    ),
  ),
  
  
  
  // 클래스 밖에
  
  // 자동 하이픈 넣어주는 함수
String formatPhoneNumber(String input) {
  input = input.replaceAll(RegExp(r'\D'), ''); // 숫자가 아닌 글자는 지우기
  if (input.length >= 4 && input.length < 7) {  // 길이가 4에서 6 사이인 경우 3번째에 하이픈 붙이기
    return '${input.substring(0, 3)}-${input.substring(3)}';
  } else if (input.length >= 7) { // 길이가 7이상인 경우, 3번째, 7번째에 하이픈 붙이기
    return '${input.substring(0, 3)}-${input.substring(3, 7)}-${input.substring(7)}';
  }
  return input;
}


class PhoneNumberFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
 
    if (oldValue.text.length > newValue.text.length) { //백스페이스가 눌렸는지 확인하는 조건
      return newValue; 
    }

    if (newValue.text.length > 1) { // 입력됐을 경우, formatPhoneNumber() 실행하기
      String formatted = formatPhoneNumber(newValue.text);
      return newValue.copyWith(text: formatted, selection: TextSelection.collapsed(offset: formatted.length));
    }

    return newValue;
  }
}

 

완료
내 컴퓨터