flutter如何实现验证码输入框
在Flutter中如何实现一个验证码输入框?我需要一个类似短信验证码的输入界面,要求每个数字有独立的方框,输入后自动跳转到下一个输入框,并且支持删除和自动聚焦。有没有现成的插件或推荐的自定义实现方案?最好能支持样式自定义和错误提示功能。
2 回复
在Flutter中实现验证码输入框,可以使用TextField结合TextEditingController和FocusNode来实现。以下是核心步骤:
- 创建控制器和焦点:
TextEditingController _controller = TextEditingController();
FocusNode _focusNode = FocusNode();
-
使用TextField: 设置
keyboardType: TextInputType.number限制数字输入,通过onChanged监听输入变化。 -
自定义UI: 常用方案是使用
Row+Container模拟单个输入框,或使用PinCodeTextField第三方库(推荐)。 -
基础实现示例:
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: List.generate(6, (index) =>
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
border: Border.all(),
),
child: Text(
index < _controller.text.length
? _controller.text[index]
: '',
),
),
),
)
TextField(
controller: _controller,
focusNode: _focusNode,
keyboardType: TextInputType.number,
maxLength: 6,
showCursor: false,
decoration: InputDecoration.collapsed(hintText: ''),
)
- 推荐方案:
直接使用
pin_code_fields库,只需几行代码即可实现完整功能,支持自定义样式和验证逻辑。
更多关于flutter如何实现验证码输入框的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中实现验证码输入框,可以使用TextField配合输入格式控制或使用第三方库。以下是两种实现方式:
1. 使用TextField自定义实现
TextField(
keyboardType: TextInputType.number,
maxLength: 6, // 验证码长度
decoration: InputDecoration(
counterText: '', // 隐藏计数器
border: OutlineInputBorder(),
hintText: '请输入验证码',
),
onChanged: (value) {
if (value.length == 6) {
// 输入完成处理
print('验证码: $value');
}
},
)
2. 使用第三方库(推荐)
在pubspec.yaml添加依赖:
dependencies:
pin_code_fields: ^7.4.0
使用示例:
PinCodeTextField(
length: 6,
obscureText: false,
animationType: AnimationType.fade,
pinTheme: PinTheme(
shape: PinCodeFieldShape.box,
borderRadius: BorderRadius.circular(5),
fieldHeight: 50,
fieldWidth: 40,
activeFillColor: Colors.white,
),
onCompleted: (pin) {
print("Completed: $pin");
},
onChanged: (value) {
print(value);
},
)
主要特性说明:
- 长度控制:通过
length参数设置验证码位数 - 输入类型:可限制为数字键盘
TextInputType.number - 样式自定义:支持边框、颜色、形状等样式定制
- 回调函数:
onChanged实时监听输入变化onCompleted输入完成时触发
推荐使用pin_code_fields库,它提供了更完善的验证码输入体验,包括自动聚焦、光标动画等功能。

