Flutter return snackbar 成功将数据发布到 API

Flutter return snackbar on successfully posting data to API

我正在尝试为向 API 发布数据的成功和失败显示一个快餐栏。条形图看起来很棒,但即使数据应该失败,它似乎也显示成功。我期望 then 仅在卡片实际成功写回条带时呈现,否则使用 catch 并显示错误

这就是未来

static Future<Payment> createPayment(context, Payment payment) async {
    final response = await http
        .post(
      Uri.parse('$stripeRef/payment/credit-card/new/${payment.userId}'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(<String, String>{
        // 'card_number': payment.cardNumber,
        'card_number': payment.cardNumber,
        'expiry_month': payment.expMonth,
        'expiry_year': payment.expYear,
        'cvv': payment.cvv
      }),
    )
        .then((response) {
      Navigator.of(context).pop(true);
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
          content: Text(
        'Successfully Added New Payment',
        textAlign: TextAlign.center,
      )));
    }).catchError((error) => ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Failed to update because of $error'))));

我认为您需要在响应中添加一些验证,并基于对响应 showSnackBar 的验证是失败还是成功。