credit card number input format flutter

Hi Guy’s Welcome to Proto Coders Point. In this flutter tutorial let’s learn How to create textfield which accept number in credit card format, I mean to say after every 4 digits entered by user there is a space.

For Example: 5487 5485 1122 4455

Our Flutter TextField will display entered credit card number as above format.

Credit Card Input Format in flutter app

In Flutter TextFormField Widget, We have a very useful property i.e. inputFormatter:[], By using it we can validate & Format our input TextField.

1. User should be able to enter only Whole Number (0 – N), He should not be able to enter special symbol’s like (. or ,) from number keyboardType. Therefore in inputFormatter we can use FilteringInputFormatter

FilteringTextInputFormatter.digitsOnly

2. User should be able to enter max 16 character in textField, Therefore in inputFormatter we can use LengthLimitingTextInputFormatter

Debit/Credit Card Number will be of 16 character length

LengthLimitingTextInputFormatter(16)

3. A Class that return’s enter credit card number by giving space after every 4th digits.

Call the below called inside inputFormatters:[]

// this class will be called, when their is change in textField
class CreditCardNumberFormater extends TextInputFormatter{
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    if(newValue.selection.baseOffset == 0){
      return newValue;
    }
    String enteredData = newValue.text;   // get data enter by used in textField
    StringBuffer buffer = StringBuffer();

    for(int i = 0;i <enteredData.length;i++){
      // add each character into String buffer
      buffer.write(enteredData[i]);
      int index = i + 1;
      if(index % 4 == 0 && enteredData.length != index){
        // add space after 4th digit
        buffer.write(" ");
      }
    }
   
    return  TextEditingValue(
      text: buffer.toString(),   // final generated credit card number
      selection: TextSelection.collapsed(offset: buffer.toString().length) // keep the cursor at end 
    );
  }

}

Flutter TextFormField InputFormatters Example:

TextFormField(
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,
                  CreditCardNumberFormater(),
                  LengthLimitingTextInputFormatter(16)

                ],
...........
.......
.......
.......
),

Complete Source Code – Flutter TextFormField Credit Card Formatters

main.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  var themeSetting = ThemeData(      // Always Create a select variable to device Theme
      primarySwatch: Colors.blue,
      textTheme: TextTheme(),
      primaryColor: Colors.green
  );

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter',
      theme: themeSetting,
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
       title: Text("Credit card input format")
      ),
      body: Padding(
        padding: const EdgeInsets.all(10.0),
        child: Form(
          child: Column(
            children: [
              TextFormField(
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,    // allow only  digits
                  CreditCardNumberFormater(),                // custom class to format entered data from textField
                  LengthLimitingTextInputFormatter(16)       // restrict user to enter max 16 characters

                ],
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                    border: InputBorder.none,
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10.0)
                    ),
                    enabledBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.grey),
                      borderRadius: BorderRadius.circular(10.0),
                    ),
                    hintText: "Enter Credit Card Number",
                    prefixIcon:  Padding(
                      padding: EdgeInsets.only(right:8.0),
                      child: Icon(Icons.credit_card),
                    ),
                  filled: true,
                  fillColor: Colors.grey[350]
                ),
              )
            ],
          ),
        ),
      )
    );
  }
}


// this class will be called, when their is change in textField
class CreditCardNumberFormater extends TextInputFormatter{
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    if(newValue.selection.baseOffset == 0){
      return newValue;
    }
    String enteredData = newValue.text;   // get data enter by used in textField
    StringBuffer buffer = StringBuffer();

    for(int i = 0;i <enteredData.length;i++){
      // add each character into String buffer
      buffer.write(enteredData[i]);
      int index = i + 1;
      if(index % 4 == 0 && enteredData.length != index){
        // add space after 4th digit
        buffer.write(" ");
      }
    }
   
    return  TextEditingValue(
      text: buffer.toString(),   // final generated credit card number
      selection: TextSelection.collapsed(offset: buffer.toString().length) // keep the cursor at end
    );
  }
}