Flutter:滑块验证,图片拼接验证

发布于:2025-07-01 ⋅ 阅读:(17) ⋅ 点赞:(0)

slider_captcha: ^1.0.2
在这里插入图片描述

  // 注册方法 - 先进行滑块验证
  void register() async {
    // 如果还未进行滑块验证,显示滑块验证弹窗
    if (!isSliderVerified) {
      Get.dialog(
        buildSliderCaptcha(Get.context!),
        barrierDismissible: true,
      );
      return;
    }
    
    // 滑块验证通过后执行注册
    await _performRegister();
  }

  // 构建滑块验证弹窗
  Widget buildSliderCaptcha(BuildContext context) {
    return Center(
      child: Container(
        decoration: BoxDecoration(
            color: Colors.white, 
            borderRadius: BorderRadius.circular(8)),
        padding: const EdgeInsets.all(16.0),
        margin: const EdgeInsets.all(16.0),
        child: SliderCaptcha(
          controller: sliderController,
          image: Image.asset(
            'assets/images/captcha.png', // 使用项目中现有的图片
            fit: BoxFit.fitWidth,
          ),
          colorBar: const Color(0xff0052D9), // 使用项目主题色
          colorCaptChar: const Color(0xff0052D9), // 拼图块颜色
          onConfirm: (value) async {
            if (value) {
              Loading.success("验证通过");
              Get.back();
              isSliderVerified = true;
              // 验证通过后继续执行注册
              await _performRegister();
            } else {
              // 验证失败,重新生成验证码
              Future.delayed(const Duration(seconds: 1)).then((_) {
                sliderController.create();
              });
              Loading.error("请重试");
            }
          },
        ),
      ),
    );
  }

  // 执行实际注册逻辑
  Future<void> _performRegister() async {
    Loading.show();
    var res = await LoginApi.register(
      UserRegisterReq(
        account: phoneController.text, 
        code: codeController.text, 
        password: passwordController.text, 
      )
    );
    if (res) {
      Loading.success('注册成功');
      // 重置滑块验证状态
      isSliderVerified = false;
      Get.back();
    } else {
      Loading.error('注册失败');
      // 注册失败,重置滑块验证状态,要求重新验证
      isSliderVerified = false;
    }
  }