Search code examples
fluttertry-catchfuturesnackbar

Flutter return snackbar on successfully posting data to API


I am trying to display a snackbar for both success and failure of posting data to an API. The bar appears to be appearing which is great, but it seems be showing the success even when the data should fail. I am expecting that the then only renders if a card is actually successfully written back to stripe, otherwise to use the catch and surface the error

This is the future

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'))));

Solution

  • I think you need to add some validation in response and on basis of the validation on response showSnackBar whether failed or success.