Open In App

Flutter – Implement Captcha Verification

Last Updated : 26 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The word CAPTCHA stands for the Completely Automated Public Turing Test to Tell Computers and Humans Apart. If you have gone through any website or app you must have seen a captcha verification during login to check whether you are human or robot. So in this article, we will learn about how to add captcha in Flutter. We will generate the captcha on the page loading, and on the refresh button click we will regenerate the new verification code. After that, we will check whether input and verification match or not. A sample video is given below to get an idea about what we are going to do in this article.

Note: We will do all this without using any packages.

Step By Step Implementation

Step by Step implementation for adding captcha in Flutter app.

Step 1: Create One basic flutter project with command

Dart




flutter create .


Create one simple project or you can use existing project

Step 2: Create basic UI for captcha verification

Dart




Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              "Enter Captacha Value",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(
              width: 10,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // Shown Captcha value to user
                Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                        border: Border.all(width: 2),
                        borderRadius: BorderRadius.circular(8)),
                    child: Text(
                      randomString,
                      style: const TextStyle(fontWeight: FontWeight.w500),
                    )),
                const SizedBox(
                  width: 10,
                ),
                // Regenerate captcha value
                IconButton(
                    onPressed: () {
                        
                    },
                    icon: const Icon(Icons.refresh)),
              ],
            ),
            const SizedBox(
              height: 10,
            ),
            // TextFormField to enter captcha value
            TextFormField(
              onChanged: (value) {
                
              },
              decoration: const InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: "Enter Captcha Value",
                  labelText: "Enter Captcha Value"),
              controller: controller,
            ),
            const SizedBox(
              height: 10,
            ),
            // To check captcha value and 
            // textediting controller value
            ElevatedButton(
                onPressed: () {
                   
                },
                child: const Text("Check")),
            const SizedBox(
              height: 10,
            ),
            // Output whether captcha is
            // correctly entered or not
            if (isVerified)
              const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [Icon(Icons.verified), Text("Verified")],
              )
            else
              const Text("Please enter value you see on screen"),
          ],
        ),
      )


In above UI we have added following things

  • Text named as Enter Captch Value
  • Container in which we will show the generate captcha

Note: You can customise the container as per your requirement. Here we have made a very simple design.

  • Textformfield to take input from user
  • Elevated Button to check captcha code and entered text is same or not
  • One more text to show the result of verification

Step 3: Add Captcha generation logic

Dart




// Logic for creating Captcha
void buildCaptcha() {
    // Letter from which we want to generate the captach
    // We have taken A to Z all small nand caps 
      // letters along with numbers
    // You can change this as per your convience
    const letters =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    const length = 6;
      
      // Length of Captcha to be generated
    final random = Random();
      
      // Select random letters from above list
    randomString = String.fromCharCodes(List.generate(
        length, (index) => letters.codeUnitAt(random.nextInt(letters.length))));
    setState(() {});
    print("the random string is $randomString");
  }


We will call this function in init state for generating captcha during page load and on refresh button to change the captcha value like this

Dart




@override
void initState() {
  super.initState();
  // To generate number
  // on loading of page
  buildCaptcha();
}


Step 4: Checking verification and input value

Dart




// To check captcha value and textediting controller value
ElevatedButton(
        onPressed: () {
               isVerified = controller.text == randomString;
                  setState(() {});
                },
                child: const Text("Check")),


In the above code we have If condition in that we are checking whether entered value and generated captcha value is same or not.If they are same then it will do verified variable as true and if not it will be false.

Step 5: Arranging all things in One screen

Let’s arrange all the things in one screen like generating logic, UI for captcha, calling its function.

Dart




Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              "Enter Captacha Value",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(
              width: 10,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // Shown Captcha value to user
                Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                        border: Border.all(width: 2),
                        borderRadius: BorderRadius.circular(8)),
                    child: Text(
                      randomString,
                      style: const TextStyle(fontWeight: FontWeight.w500),
                    )),
                const SizedBox(
                  width: 10,
                ),
                // Regenerate captcha value
                IconButton(
                    onPressed: () {
                      buildCaptcha();
                    },
                    icon: const Icon(Icons.refresh)),
              ],
            ),
            const SizedBox(
              height: 10,
            ),
            // TextFormField to enter captcha value
            TextFormField(
              onChanged: (value) {
                setState(() {
                  isVerified = false;
                });
              },
              decoration: const InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: "Enter Captcha Value",
                  labelText: "Enter Captcha Value"),
              controller: controller,
            ),
            const SizedBox(
              height: 10,
            ),
            // To check captcha value and 
            // textediting controller value
            ElevatedButton(
                onPressed: () {
                  if (controller.text == randomString) {
                    print("Checked");
  
                    isVerified = true;
                  } else {
                    isVerified = false;
                  }
                  setState(() {});
                },
                child: const Text("Check")),
            const SizedBox(
              height: 10,
            ),
            // Output whether captcha is correctly entered or not
            if (isVerified)
              const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [Icon(Icons.verified), Text("Verified")],
              )
            else
              const Text("Please enter value you see on screen"),
          ],
        ),
      )


Complete Code

Dart




import 'dart:math';
  
import 'package:flutter/material.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a blue toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
        useMaterial3: true,
      ),
      home: const CaptachaVerification(),
    );
  }
}
  
class CaptachaVerification extends StatefulWidget {
  const CaptachaVerification({super.key});
  
  @override
  State<CaptachaVerification> createState() => _CaptachaVerificationState();
}
  
class _CaptachaVerificationState extends State<CaptachaVerification> {
  String randomString = "";
  bool isVerified = false;
  TextEditingController controller = TextEditingController();
  // Logic for creating Captcha
  void buildCaptcha() {
    // Letter from which we want to generate the captach
    // We have taken A to Z all small nand 
    // caps letters along with numbers
    // You can change this as per your convience
    const letters =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    const length = 6;
    // Length of Captcha to be generated
    final random = Random();
    // Select random letters from above list
    randomString = String.fromCharCodes(List.generate(
        length, (index) => letters.codeUnitAt(random.nextInt(letters.length))));
    setState(() {});
    print("the random string is $randomString");
  }
  
  @override
  void initState() {
    super.initState();
    // To generate number on loading of page
    buildCaptcha();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 2,
        title: const Text("Flutter Captcha Verification"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              "Enter Captacha Value",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(
              width: 10,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // Shown Captcha value to user
                Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                        border: Border.all(width: 2),
                        borderRadius: BorderRadius.circular(8)),
                    child: Text(
                      randomString,
                      style: const TextStyle(fontWeight: FontWeight.w500),
                    )),
                const SizedBox(
                  width: 10,
                ),
                // Regenerate captcha value
                IconButton(
                    onPressed: () {
                      buildCaptcha();
                    },
                    icon: const Icon(Icons.refresh)),
              ],
            ),
            const SizedBox(
              height: 10,
            ),
            // TextFormField to enter captcha value
            TextFormField(
              onChanged: (value) {
                setState(() {
                  isVerified = false;
                });
              },
              decoration: const InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: "Enter Captcha Value",
                  labelText: "Enter Captcha Value"),
              controller: controller,
            ),
            const SizedBox(
              height: 10,
            ),
            // To check captcha value and 
            // textediting controller value
            ElevatedButton(
                onPressed: () {
                  isVerified = controller.text == randomString;
  
                  setState(() {});
                },
                child: const Text("Check")),
            const SizedBox(
              height: 10,
            ),
            // Output whether captcha is correctly entered or not
            if (isVerified)
              const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [Icon(Icons.verified), Text("Verified")],
              )
            else
              const Text("Please enter value you see on screen"),
          ],
        ),
      ),
    );
  }
}


Here you have successfully implemented the captcha verification code without using any packages.

Output:

Image:

Basic UI

WhatsApp-Image-2023-11-11-at-32300-PM

When Captcha is verified

WhatsApp-Image-2023-11-11-at-32610-PM-(1)

When it is not verified

WhatsApp-Image-2023-11-11-at-32610-PM

Video:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads