Flutter:OTP页面PinCodeTextField空值验证与another_flushbar触发实现
OTP页面空值验证实现方案
我正在开发OTP页面,使用了pin_code_fields组件。现在需要实现验证逻辑:当用户点击提交按钮时,如果PinCodeTextField内容为空,就通过已集成的another_flushbar组件显示提示信息“你的输入框仍为空”。请问该如何实现?
我的PinCodeTextField代码
TextEditingController textEditingController = TextEditingController(); PinCodeTextField( appContext: context, keyboardType: TextInputType.number, length: 4, animationType: AnimationType.none, cursorColor: Colors.black, controller: textEditingController, onChanged: (value) {}, pinTheme: PinTheme( shape: PinCodeFieldShape.box, selectedColor: Colors.white, borderRadius: BorderRadius.circular(Dimensions.radius10), fieldHeight: Dimensions.height50, fieldWidth: Dimensions.width50, inactiveColor: Colors.white, activeColor: Colors.white, ), onCompleted: (value) { print("Completed"); }, ),
我的another_flushbar工具类代码
class Utils{ static void flushBarErrorMessage(String message, BuildContext context) { showFlushbar( context: context, flushbar: Flushbar( forwardAnimationCurve: Curves.decelerate, margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), padding: const EdgeInsets.all(15), titleColor: Colors.white, duration: const Duration(seconds: 3), borderRadius: BorderRadius.circular(10), reverseAnimationCurve: Curves.easeInOut, icon: const Icon( Icons.error, size: 28, color: Colors.white, ), flushbarPosition: FlushbarPosition.TOP, positionOffset: 20, message: message, backgroundColor: Colors.red, )..show(context)); } }
我的提交按钮代码
ElevatedButton( onPressed: () { // _confirmOtp(); }, style: ElevatedButton.styleFrom( backgroundColor: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Dimensions.radius10)), minimumSize: Size.fromHeight(Dimensions.height40), ), child: BigText(text: LanguageStringKeys.instance.Submit.tr, color: Colors.grey), ),
实现方案
直接在提交按钮的点击回调中添加空值判断逻辑即可,修改后的按钮代码如下:
ElevatedButton( onPressed: () { // 检查OTP输入框是否为空 if (textEditingController.text.isEmpty) { // 调用工具类显示错误提示 Utils.flushBarErrorMessage("你的输入框仍为空", context); } else { // 输入内容不为空时,执行原本的OTP验证逻辑 _confirmOtp(); } }, style: ElevatedButton.styleFrom( backgroundColor: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Dimensions.radius10)), minimumSize: Size.fromHeight(Dimensions.height40), ), child: BigText(text: LanguageStringKeys.instance.Submit.tr, color: Colors.grey), ),
逻辑说明
- 通过
textEditingController.text.isEmpty判断输入框内容是否为空 - 为空时直接调用已封装的
Utils.flushBarErrorMessage方法显示提示 - 输入内容合法时,继续执行原本的
_confirmOtp()验证流程
内容的提问来源于stack exchange,提问作者user12790690
相关产品推荐
相关产品推荐

