Frontend/Flutter

[Flutter] TextField, CupertinoTextField에 숫자만 입력되게 하기

김룹 2024. 2. 21. 10:40

TextField에서 사용자에게 받는 내용을 숫자로만 제한해야할 때가 있다.

keyboardType 옵션을 사용해서 숫자 키패드만 나오게 할 수가 있는데, 이럴 경우 문자열 붙여넣기가 가능하여 문자열이 들어갈 수 있다.

 

 

 

 

💡해결방법

숫자를 완전히 허용하지 않게 하려면, inputFormatters 옵션에서 필터링을 주면 됨!

 

 

 

  final _costController = TextEditingController();

	CupertinoTextField(
          cursorColor: style.colors['main1'],
          placeholder: '금액을 입력해주세요',
          padding: EdgeInsets.all(13),
          controller: _costController,
          onChanged: onChanged,
          maxLines: 1,
          keyboardType: TextInputType.number,
          inputFormatters: [
              FilteringTextInputFormatter.allow(
                RegExp('[0-9]'),
              )
            ],
        ),

✔️ TitleInput은 CupertinoTextField를 직접 커스텀한 위젯입니다!

✔️ 0~9까지의 숫자만 허용하겠다는 의미! (allow 사용)