You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Form Validator失效求助:验证逻辑在initPayment中不生效

Flutter Form Validator 在 initPayment 函数中失效问题排查

核心问题分析

  • TextFormField 未正确闭合:你的代码中TextFormField缺少闭合的括号和逗号,导致Widget树结构异常,Form无法正确关联输入框的验证器,直接造成_formKey.currentState.validate()无法触发校验逻辑。
  • 调用 initPayment 前提前解析输入值:在MaterialButton的onPressed回调中,你直接执行double.parse(_reloadEditingController.text),若输入为空或非数字,这一步会直接抛出异常,根本无法进入initPayment函数执行校验。

修复方案

步骤1:修复Widget结构错误

补充TextFormField的闭合标签,确保Form的子Widget结构完整:

Form(
  key: _formKey,
  child: Column(
    children: [
      TextFormField(
        inputFormatters: <TextInputFormatter>[],
        style: TextStyle(
          color: Colors.white,
        ),
        controller: _reloadEditingController,
        keyboardType: TextInputType.phone,
        autovalidateMode: AutovalidateMode.onUserInteraction,
        validator: (value) {
          if (value!.isEmpty) {
            return 'Please enter min value';
          }
          // 新增数字格式校验,避免后续parse报错
          if (double.tryParse(value) == null) {
            return 'Please enter a valid number';
          }
          return null;
        },
      ), // 补充缺失的闭合括号和逗号
      Container(
        width: 320,
        child: MaterialButton(
          onPressed: () async {
            // 直接调用initPayment,不再提前解析文本
            await initPayment(
              email: email,
              context: context);
          },
          color: Color(0xFF006e6e),
          elevation: 8,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(13),
          ),
          child: Padding(
            padding: EdgeInsets.symmetric(vertical: 14),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "Reload E-Wallet",
                  style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 20),
                )
              ],
            ),
          ),
        ),
      ),
    ],
  ),
)

步骤2:调整initPayment函数逻辑

移除冗余的amount参数,在校验通过后再处理输入值:

Future<void> initPayment(
    {required String email,
    required BuildContext context}) async {
  final isValid = _formKey.currentState!.validate();

  if (isValid) {
    try {
      double s = double.parse(_reloadEditingController.text);
      // 1. 创建支付意图
      final response = await http.post(
          Uri.parse(
              'https://us-central1-fiverr-3402e.cloudfunctions.net/stripePaymentIntentRequest'),
          body: {
            'email': email,
            'amount': (s * 100).toString(),
          });

      final jsonResponse = jsonDecode(response.body);
      log(jsonResponse.toString());
      // 2. 初始化支付表单
      await Stripe.instance.initPaymentSheet(
          paymentSheetParameters: SetupPaymentSheetParameters(
        paymentIntentClientSecret: jsonResponse['paymentIntent'],
        merchantDisplayName: 'IIUM Freelance',
        customerId: jsonResponse['customer'],
        customerEphemeralKeySecret: jsonResponse['ephemeralKey'],
      ));
      await Stripe.instance.presentPaymentSheet();
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Payment is successful'),
        ),
      );

      try {
        await FirebaseFirestore.instance
            .collection("users")
            .doc(widget.userID)
            .update({"balance": balance + s});
        getUserData();
      } catch (error) {}
    } catch (errorr) {
      if (errorr is StripeException) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content:
                Text('An error occured ${errorr.error.localizedMessage}'),
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('An error occured $errorr'),
          ),
        );
      }
    }
  }
}

额外优化建议

  • 在验证器中添加金额最小值校验(比如if (double.parse(value) < 1) return 'Minimum amount is 1'),进一步提升用户体验
  • 可以给double.parse添加try-catch兜底,避免极端情况下的异常崩溃

内容的提问来源于stack exchange,提问作者luffy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 15:15:42