Reading list Switch to dark mode

    Implement Credit Card View In Flutter.

    Updated 22 December 2023

    In this blog post, we will learn how to implement a credit card view in a Flutter application.

    By utilizing the flutter_credit_card package, we will demonstrate how to quickly incorporate a credit card user interface with card recognition into your Flutter projects.

    You may also check our Flutter app development company page.

    Introduction:-

    A Flutter package that supports inputting credit card information and includes a card flip animation for an enhanced UI experience.

    A-credit-card-widget-package-that-supports-inputting-card-information-and-has-card-flip-animation.-You-can-quickly-implement-the-Credit-cards-UI-with-a-Flutter-package-thanks-to-Card-detection

    Implementation:-
    First, we need to create a new flutter project and add the following dependencies in the pubspec.yaml file.

    dependencies:
      flutter
        sdk: flutter
      flutter_credit_card: ^3.0.6

    Now, run the command “flutter pub get” to add the dependencies.

    Start your headless eCommerce
    now.
    Find out More

    To include the required package, please add it to your class.

    import 'package:flutter_credit_card/flutter_credit_card.dart';

    We will first create CreditCardWidget():

    Some essential fields in CreditCardWidget(), creating card number, which enables the user to enter their card number for card identification, must be null.

    The user can input the name that appears on the front of their credit card using the CardHolderName field.

    Users can input their card’s expiration date in the month and year format in the expiry date field.

    The cvv Code field allows the user to input their three-digit cvv number, which can be found printed on the back of their card.

      CreditCardWidget(
                    cardNumber: cardNumber,
                    expiryDate: expiryDate,
                    cardHolderName: cardHolderName,
                    cvvCode: cvvCode,
                    bankName: 'Axis Bank',
                    showBackView: isCvvFocused,
                    obscureCardNumber: true,
                    obscureCardCvv: true,
                    isHolderNameVisible: true,
                    cardBgColor: Colors.blueGrey.shade700,
                    isSwipeGestureEnabled: true,
                    onCreditCardWidgetChange:
                        (CreditCardBrand creditCardBrand) {},
                    customCardTypeIcons: <CustomCardTypeIcon>[
                      CustomCardTypeIcon(
                        cardType: CardType.mastercard,
                        cardImage: Image.asset(
                          'assets/images.png',
                          height: 48,
                          width: 48,
                        ),
                      ),
                    ],
                  ),

    The formkey will be added to this CreditCardForm(). The ultimate globalkey is user-created.

    final GlobalKey<FormState> formKey = GlobalKey<FormState>();

    We will now create the onCreditCardModel, and we can add the cardNumber, expiryDate, cvv, and other Strings to it.

    void onCreditCardModel(CreditCardModel? creditCardModel) {
        setState(() {
          cardNumber = creditCardModel!.cardNumber;
          expiryDate = creditCardModel.expiryDate;
          cardHolderName = creditCardModel.cardHolderName;
          cvvCode = creditCardModel.cvvCode;
          isCvvFocused = creditCardModel.isCvvFocused;
        });
      }

    We will provide customers with the option to create a personalized box displaying their credit card number using NumberDecoration.

    Users may write an expiration date on this decoration box and display it on their credit card by using the expiryDateDecoration term.

    Users may enter a CVV code in this decoration box using the cvv Code Decoration command, and the card will display the code on our credit card in an animated reversal.

    CardHolderDecoration allows users to decorate their credit cards by writing a person’s name on the front and displaying it.

    import 'package:flutter/material.dart';
    import 'package:flutter_credit_card/credit_card_brand.dart';
    import 'package:flutter_credit_card/flutter_credit_card.dart';
    
    class CreditCard extends StatefulWidget {
      const CreditCard({super.key});
    
      @override
      State<StatefulWidget> createState() {
        return CreditCardView();
      }
    }
    
    class CreditCardView extends State<CreditCard> {
      String cardNumber = '';
      String expiryDate = '';
      String cardHolderName = '';
      String cvvCode = '';
      bool isCvvFocused = false;
      OutlineInputBorder? border;
      final GlobalKey<FormState> formKey = GlobalKey<FormState>();
    
      @override
      void initState() {
        border = const OutlineInputBorder(
          borderSide: BorderSide(
            color: Colors.black,
          ),
        );
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          resizeToAvoidBottomInset: false,
          body: SafeArea(
            child: Column(
              children: <Widget>[
                const SizedBox(
                  height: 30,
                ),
                CreditCardWidget(
                  cardNumber: cardNumber,
                  expiryDate: expiryDate,
                  cardHolderName: cardHolderName,
                  cvvCode: cvvCode,
                  bankName: 'Axis Bank',
                  showBackView: isCvvFocused,
                  obscureCardNumber: true,
                  obscureCardCvv: true,
                  isHolderNameVisible: true,
                  cardBgColor: Colors.blueGrey.shade700,
                  isSwipeGestureEnabled: true,
                  onCreditCardWidgetChange: (CreditCardBrand creditCardBrand) {},
                  customCardTypeIcons: <CustomCardTypeIcon>[
                    CustomCardTypeIcon(
                      cardType: CardType.mastercard,
                      cardImage: Image.asset(
                        'assets/images.png',
                        height: 48,
                        width: 48,
                      ),
                    ),
                  ],
                ),
                Expanded(
                  child: SingleChildScrollView(
                    child: Column(
                      children: <Widget>[
                        CreditCardForm(
                          formKey: formKey,
                          obscureCvv: true,
                          obscureNumber: true,
                          cardNumber: cardNumber,
                          cvvCode: cvvCode,
                          isHolderNameVisible: true,
                          isCardNumberVisible: true,
                          isExpiryDateVisible: true,
                          cardHolderName: cardHolderName,
                          expiryDate: expiryDate,
                          themeColor: Colors.blue,
                          textColor: Colors.black,
                          cardNumberDecoration: InputDecoration(
                              labelText: 'Number',
                              hintText: 'XXXX XXXX XXXX XXXX',
                              hintStyle: const TextStyle(color: Colors.black),
                              labelStyle: const TextStyle(color: Colors.black),
                              focusedBorder: border,
                              enabledBorder: border,
                              errorBorder: const OutlineInputBorder(
                                borderSide: BorderSide(
                                  color: Colors.red,
                                ),
                              )),
                          expiryDateDecoration: InputDecoration(
                            hintStyle: const TextStyle(color: Colors.black),
                            labelStyle: const TextStyle(color: Colors.black),
                            focusedBorder: border,
                            enabledBorder: border,
                            errorBorder: const OutlineInputBorder(
                              borderSide: BorderSide(
                                color: Colors.red,
                              ),
                            ),
                            labelText: 'Expired Date',
                            hintText: 'XX/XX',
                          ),
                          cvvCodeDecoration: InputDecoration(
                            hintStyle: const TextStyle(color: Colors.black),
                            labelStyle: const TextStyle(color: Colors.black),
                            focusedBorder: border,
                            enabledBorder: border,
                            errorBorder: const OutlineInputBorder(
                              borderSide: BorderSide(
                                color: Colors.red,
                              ),
                            ),
                            labelText: 'CVV',
                            hintText: 'XXX',
                          ),
                          cardHolderDecoration: InputDecoration(
                            hintStyle: const TextStyle(color: Colors.black),
                            labelStyle: const TextStyle(color: Colors.black),
                            focusedBorder: border,
                            enabledBorder: border,
                            labelText: 'Card Holder',
                          ),
                          onCreditCardModelChange: onCreditCardModel,
                        ),
                        const SizedBox(
                          height: 20,
                        ),
                        const SizedBox(
                          height: 20,
                        ),
                        GestureDetector(
                          onTap: () {
                            if (formKey.currentState!.validate()) {
                              _showValidDialog(context);
                              print('valid!');
                            } else {
                              print('invalid!');
                            }
                          },
                          child: Container(
                            margin: const EdgeInsets.symmetric(
                                horizontal: 16, vertical: 8),
                            decoration: BoxDecoration(
                              color: Colors.black87,
                              borderRadius: BorderRadius.circular(8),
                            ),
                            padding: const EdgeInsets.symmetric(vertical: 15),
                            width: double.infinity,
                            alignment: Alignment.center,
                            child: const Text(
                              'Validate',
                              style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'halter',
                                fontSize: 14,
                                package: 'flutter_credit_card',
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    
      _showValidDialog(
        BuildContext context,
      ) {
        return showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text(
                "Valid",
              ),
              content: const Text("Your card successfully valid !!!"),
              actions: [
                TextButton(
                    child: const Text(
                      "Ok",
                      style: TextStyle(fontSize: 18, color: Colors.black),
                    ),
                    onPressed: () {
                      Navigator.of(context).pop();
                    }),
              ],
            );
          },
        );
      }
    
      void onCreditCardModel(CreditCardModel? creditCardModel) {
        setState(() {
          cardNumber = creditCardModel!.cardNumber;
          expiryDate = creditCardModel.expiryDate;
          cardHolderName = creditCardModel.cardHolderName;
          cvvCode = creditCardModel.cvvCode;
          isCvvFocused = creditCardModel.isCvvFocused;
        });
      }
    }

    Output:-

    The Flutter package simplifies the implementation of a credit card UI with card recognition.

    Conclusion:-

    We have completed the implementation of creating a Credit Card View in Flutter.

    Check here for more interesting blogs –https://mobikul.com/blog/.

    Hope this blog helped you to better understand the Implement Credit Card View In Flutter.

    “Thank you for taking the time to read this blog.”

    References:-

    https://pub.dev/packages/flutter_credit_card

    https://medium.flutterdevs.com/credit-card-view-in-flutter-f415f9578e03

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home