Home Blog Page 56

Flutter reCaptcha Verification – I am not a robot captcha verify

0
flutter recaptcha verification in flutter

Hi Guys, Welcome to Proto Coders Point.

In this flutter tutorial, We will learn how to integrate recaptcha verification in flutter app i.e. i am not a robot validation process in flutter.

What is reCAPTCHA

The recaptcha is very useful service when you want to protect your website from spam users and as flutter can we hosted as web app, we need to protect it, so it better to integrate recaptcha in flutter app.

recaptcha validation uses advanced risk analysis technique to detect human user or bot & support if captcha found any spam then it prompt a challenge to verify that you are a human( a real user ).

SignUp – How to get Google recaptcha API key

To use recaptcha in flutter app, you need to sign up for captcha API key for your site ip/domain

The captcha consist of 2 keys

  1. Site Key: used to show captcha verification widget on your site.
  2. Secret Key: is used for authentiation a communication between application & recaptcha server to verify user’s response.

Let’s get Started

In this project we are going to load a HTML page from Assets directory & display the webpage into our flutter app.

So in HTML page (index.html) will implement recaptcha verify & then show index.html web page into our flutter app.


To Load Web Page into flutter app we need a library i.e. webview_flutter_plus.

Video Tutorial

Implement recaptcha in flutter by loading WebPage in flutter App

Step 1: Add Webview Plus dependencies in flutter project

Open pubspec.yaml file & under dependencies section add webview_flutter_plus package.

dependencies:
  webview_flutter_plus:

Now run ‘flutter pub get’ command in IDE terminal else hit pub get button.


Step 2: Add Internet uses permission & cleartraffic

As we are making internet calls to verify captcha, we need internet access permission.

To add Intermet permission goto AndroidManifest.xml file

android > app > src > main > AndroidManifest.xml

Add the 3 permission in manifest tag

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

then in <application> tag add usesClearTextTraffic = true

refer screenshot below

add internet permission and clear text traffic android

Step 3: Create a Webpage under directory in flutter project

Right click on project > New > Directory (create assets folder)

and in assets folder create one more directory (webpages), as shown in below screenshot

how to create directory in flutter project

Now in assets/webpages/ folder create a file & name it as index.html and copy paste below html code

recaptcha code

index.html

replace data-site-key with your own recaptcha API key as we have created in google recaptcha signup.

<!DOCTYPE html>
<html>
<head>
    <title>reCAPTCHA</title>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body style='background-color: aqua;'>
<div style='height: 60px;'></div>
<form action="?" method="POST">
    <div class="g-recaptcha"
         data-sitekey="6Ldqd90cAAA- your api key here-xSi3o7mC"
         data-callback="captchaCallback"></div>

</form>
<script>
      function captchaCallback(response){
        //console.log(response);
        if(typeof Captcha!=="undefined"){
          Captcha.postMessage(response);
        }
      }
    </script>
</body>
</html>

<html>
<body>

Step 5: loading index.html page in flutter webview

main.dart

Explanation of below source code

As we have added Webview_flutter_plus package in our flutter project, thus we can make use of WebViewPlus widget to load website in flutter app.

In WebViewPlus widget, we have a method onWebViewCreated() that help us to load webpages from assets folder i.e. assets/webpages/index.html

Then by using javascriptChannels, we will get response or captcha server response and then navigate the user to next page i.e. Welcome Page after successful verification of captcha in flutter.

import 'package:flutter/material.dart';
import 'package:flutter_recaptcha/WelcomePage.dart';
import 'package:webview_flutter_plus/webview_flutter_plus.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

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

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: WebViewPlus(
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (controller){
          controller.loadUrl("assets/webpages/index.html");
        },
        javascriptChannels: Set.from([
          JavascriptChannel(name: 'Captcha', onMessageReceived: (JavascriptMessage message){
            Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => WelcomePage()));
          })
        ]),
      )
    );
  }
}

Step 6: Create a WelcomePage.dart

WelcomePage.dart

import 'package:flutter/material.dart';

class Welcomeage extends StatelessWidget {
  const WelcomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("Welcome",style: TextStyle(fontSize: 20),),
      ),
    );
  }
}

Spy Number Program in Dart Language

0
dart program to check spy number

Hi Guys, Welcome to Proto Coders Point.

In this Dart Programming Tutorial, will learn what is a spy number and write a dart programs to check if the given number is spy number or not.

A spy number program is the most frequently programming logic program that is been asked in technical round of job interview.

What is a spy number

A Integer number is been split into individual digits, and the sum and product is found, if the sum & product are equal then it’s called as spy number.

Spy Number Example

Let’s us take a number ‘123’ and then split it into individual digit number (1, 2, 3) and let’s check where the number is spy or not a spy, so to find it we need to get sum and product of it Eg:

Sum = (1 + 2 + 3) = 6.

Product = ( 1 * 2 * 3) = 6

If you observe sum and product are equal, Therefore, 123 is a spy number

dart program to check given number is spy number or not

Algorithm to check spy number in dart

  1. Input num
  2. Declare three variable sum and product, lastdigit, initialize set value of sum = 0, product = 1.
  3. Find the last digit of given number Eg: (n%10) can be done using module operator.
  4. Add the last digit to sum variable Eg: sum = sum + lastdigit.
  5. Do multiplication using lastdigit Eg: product = product * lastdigit.
  6. Now remove last digit from num, to do so Divide num by 10.
  7. Goto step 3, loop run until num become 0.
  8. now if final sum and product are same/equal, then the given number(num) is a spy number else not a spy number.

Dart program to check if given number is spy number

import 'dart:io';
void main() {
  late int num; 
 int  product = 1, sum = 0, lastdigit;
  print('Enter a number to check for spy number');
  num = int.parse(stdin.readLineSync()!);
  
  while(num>0){
    lastdigit = num % 10;
    sum = sum +lastdigit;

    product = product * lastdigit;

    num = num~/10;
  }

  if(sum == product){
    print("The Entered Number is Spy number");
  }else{
    print("The Entered Number is Not a Spy number");
  }
}

output


Print all spy number from 1 to n given range in dart program

import 'dart:io';

bool checkSpy(int number){
   int  product = 1, sum = 0, lastdigit;
   while(number>0){
    lastdigit = number % 10;
    sum = sum +lastdigit;

    product = product * lastdigit;

    number = number~/10;
  }

  if(sum == product)
  return true;

  return false;
}
void main() {
   int startrange= 0, highrange = 0; 
 
  print('Enter Start Range to check spy number');
  startrange = int.parse(stdin.readLineSync()!);


   print('Enter High Range to check spy number');
   highrange = int.parse(stdin.readLineSync()!);


   print("");

   print("Spy Numbers Between $startrange  to $highrange are ");


   for(int i=startrange; i<=highrange;i++){
     if(checkSpy(i)){
       print("$i");
     }
   }
  

}

output

Dart Program to calculate product / multiplication of 2 numbers without *

0

Hi Guys, Welcome to Proto Coders Point, Here is a dart program to find product of 2 numbers without using * operator.

Dart program find multiplication of 2 number without * operator

In this dart program, we will not use multiplication operator i.e. *, Instead we will use iteration/loop technique to find the product of 2 number in dart program without * operator.

Product of 2 number program in dart language – Source Code

void main(){
  int a = 2, b = 3, result;
  result =product(a, b);
  print('$result');
}

// calculate multiplication and return the result
int product(int a,int b){
  int temp =0;
  while(b != 0){
    temp += a;
    b--;
  }
  return temp;
}

output

Program Explanation

In the above dart program,

We habe initialize number to 2 variables a & b, & then passing a,b values to a functon ‘product()’, that will perform multiplication without * operator.

In product() function, we have declared a temp variable as ‘0’.

The while loop, check if ‘b’ variable is not equal to ‘0’, if the while condition is true then execute the iteration loop.

So, inside while loop, we are adding the value of ‘temp’ + ‘a’ variable & then decrement value ‘b’ by -1.

There when b == 0, i.e. b !=0 (condition become false)exit the loop, & therefore we have product of a * b in temp variable, which is returned by product function & this we are print multiplication of 2 numbers on console without using dart arithmetic operator.

How to create Scratch Card in Flutter using Scratcher Package

0
flutter scratch card
flutter scratch card

Hi Guys, Welcome to Proto Coders Point.

Giving cashback, rewards & different kinds of online shopping voucher is a clean move to market your app and keep your app users engaged using your application on daily basics, rewarding scratch card rewards is like a lottery to your app user.

In this Flutter tutorial Article, We will learn how to add a scratch card in flutter app, so will dive into how to implement scratch card in flutter using scratcher package.

What is a Scratch Card reward method

A Scratch Card is mostly used to excite or make user feel enthusiastic to know the offer prizes or cashback reward given to the user.

Now a days a scratch card rewarding is most treading way to attract a user & most of the famous shopping application & UPI payment app make user of scratchCard to reward its’s customers.

Flutter Scratcher Example Demo

The above gif demo image, shows how to create a scratch card in flutter using scratcher plugin in your flutter application.

Complete Source code is below at the end please check it out after learning the basics.

So on button press we will simply show a dialog, which will have flutter scratcher – scratch card. then a user can simply rub his finger on the card to reveal or grab the cashback or reward offers.


Scratcher Flutter

Let’s get Started

Let’s install scratcher widget in your futter application as external package

Step 1: Add scratcher dependencies

open pubspec.yaml file & under dependencies add scratcher package

dependencies:
  scratcher: ^ #latest version

now hit pub get button in pubspec.yaml file or run a command in IDE Terminal.

"flutter pub get"

Step 2: Import scratcher.dart

Then, Once you have successfully added the dependencies plugin, so to use it you need to import scratcher.dart where required

import 'package:scratcher/scratcher.dart';

then, you are good to create scratch card in flutter.


Scratcher Snippet Code Explained below

Scratcher(
  color: Colors.red,
  brushSize: 35,
  threshold: 40,
  onChange: (value) => print("$value%  Scratched"),
  onThreshold: () => print("Reached Threshold..!!"),
  child: Container(
    height: 300,
    width: 300,
    color: Colors.green,
  ),
)

Properties of Scratcher Widget

PropertiesDescription
color:Give color to scratching card
image:Instead of simple color on cardm you can declare a image on card.
brushSize:Define a size to brush, give size to scratch the card
threshold:Design/ set a percentage level of wiping. Eg: threshold : 50
onThreshold:() =>When user wipe 50% of card onThreshold will be called
onChange:(value)=>This callback will be called every time when new part of card is been scratched.
child:A Widget that is behind the scratcher widget, This is actual reward been shown to user.
key:To contoller the scratcher.

This are some properties that we will use in our app below, To learn about more properties visit official library page.

Programmatically reset or reveal the reward begin card

By asigning a GolbalKey to scratcher widget we can easily control it.

Let’s check with a snippet example

Create a Golbal key using type as scratcherState

final scratchKey = GlobalKey<ScratcherState>();

Then assign it to Scratcher Widget as below

 Scratcher(
              key: scratchKey ,
..................
)

and thus you can easily control it as shown below

Here, How to reset scratcher Widget

   ElevatedButton(onPressed: (){
              scratchKey.currentState?.reset(duration: Duration(milliseconds: 2000));
         
 }, child: Text('Reset')),

Here’s how to reveal the scratcher reward

ElevatedButton(onPressed: (){
              scratchKey.currentState?.reveal(duration: Duration(milliseconds: 2000));
}, child: Text('Reveal'))


Complete Project Source Code

Flutter Scratcher widget Example

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

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

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final scratchKey = GlobalKey<ScratcherState>();

  double _opacity = 0.0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
                onPressed: () {
                  scratchDialog(context);
                },
                child: Text('Show Dialog for Reward')),
            ElevatedButton(
                onPressed: () {
                  scratchKey.currentState
                      ?.reset(duration: Duration(milliseconds: 2000));
                },
                child: Text('Reset')),
            ElevatedButton(
                onPressed: () {
                  scratchKey.currentState
                      ?.reveal(duration: Duration(milliseconds: 2000));
                },
                child: Text('Reveal'))
          ],
        ),
      ),
    );
  }

  Future<void> scratchDialog(BuildContext context) async {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30)),
              title: const Align(
                alignment: Alignment.center,
                child: Text('Yo Yo, You earned a reward..!!'),
              ),
              content: StatefulBuilder(
                builder: (context, StateSetter setState) {
                  return Scratcher(
                    accuracy: ScratchAccuracy.medium,
                    threshold: 50,
                    onThreshold: () {
                      setState(() {
                        _opacity = 1;
                      });
                    },
                    color: Colors.redAccent,
                    onChange: (value) => print('Progress $value%'),
                    brushSize: 20,
                    child: AnimatedOpacity(
                      duration: Duration(milliseconds: 1000),
                      opacity: _opacity,
                      child: Container(
                          width: 150,
                          height: 150,
                          child: const Image(
                              image: AssetImage('assets/reward.png'))),
                    ),
                  );
                },
              ));
        });
  }
}

Flutter White Splash Screen – How to Change splash screen in flutter

0
flutter white splash screen change design
flutter white splash screen change design

Hi Guys, Welcome to Proto Coders Point, I recently got a comment question from one of my youtube channel subscriber saying ‘How do I change default white splash screen in flutter’.

So that’s the reason I have created a video tutorial on youtube on remove white splash screen in flutter’ & now wrote a step by step guide article on ‘flutter change default splash screen’.

Can we remove Flutter Default Splash Screen

Flutter Default splash screen cannot be removed from native Android/iOS context, Even if you remove the while splash screen backgound code, the app will still show a black screen until flutter draws loads it’s first frame & that’s offcourse will be bad experience to user seeing black blank screen as splashscreen on start.

Let’s get started

Let’s Check how to change Flutter White Screen on start

Android

Make changes in launch_background.xml

In your Flutter Project Android Module

Android/app/src/main/res/drawable folder

In drawable, you will find a file ‘launch_background.xml’, that’s where you need to make splashscreen design changes & make it work.

Change Splash screen background

Edit with your desired flutter splash screen backgound color

<item android:drawable="@android:color/white" />  

Change Image/Icons logo in SplashScreen

copy/paste a image logo under drawable folder of your android module and paste below code in launch_background.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/white" />

    <!-- You can insert your own image assets here -->
    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/launchimage" />
    </item>
</layer-list>

How to add text in default splashscreen in flutter android

You cannot add TextView in flutter android drawable layer-list item, but you can acheive adding Text in Default splashscreen by simply creating a png image file of text and add it using <bitmap>

Eg:

<item android:top="60dp">
    <bitmap
        android:gravity="center"
        android:tint="@android:color/white"
        android:src="@drawable/text"/>
</item> 

and that’s how to add your own custome designed splashscreen in flutter.

Flutter SplashScreen not working

For Android API level 21 & above, launch_background.xml will be used from drawable-v21, therefore you need to make changes in drawable-v21/launch_background.xml.

To do so open Flutter App Android Module as ‘open for editing in Android Studio’


Flutter Splash Screen Gradient Example:

<?xml version="1.0" encoding="utf-8"?><!-- Modify this file to customize your launch splash screen -->

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <gradient
                android:centerX="0.5"
                android:centerY="0.3"
                android:endColor="#064BFA"
                android:gradientRadius="300dp"
                android:startColor="#b7e9c9"
                android:type="radial" />
        </shape>
    </item>

    <item
        android:width="150dp"
        android:height="150dp"
        android:gravity="center">
        <bitmap android:src="@drawable/launchimage" />

    </item>

</layer-list>

result

flutter change default white splash screen to gradient color with image logo

For iOS

1. Open the project in iOS Module in XCode

if you are using macBook then open flutter iOS module in XCode IDE.

2. Go to Assets.xcassets folder

In iOS module go to ios/Runner folder, then you see Assets.xcassets > LaunchImage.imageset folder

If you are using XCode IDE in macbook then you can simple drop and drop image under LaunchImage as shown below

3. Now Open LaunchScreen.storyboard

Click on the view and on the right panel click the down arrow like symbol change properties like background and content mode according to your need.

Now Select Image on the storyboard

Now on the right panel click the down arrow like symbol gain and change its properties as per need.

else is you are not in Apple macbook, so you can use XCode editor, you need to add image manually.

Paste same image logo of different pixel and name it as:

  • LaunchImage.png
  • LaunchImage@2x.png
  • LaunchImage@3x.png

How to open app settings in flutter – App_Settings package

0
Flutter Open App Setting, bluetooth, wifi, location settings
Flutter Open App Setting, bluetooth, wifi, location settings

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial Article we will learn how to open app settings in flutter.

Flutter App_Settings Package

A Flutter package by which you can easily open Android & iOS devices settings pages such as: Open App Settings, Location Settings, device, Bluetooth Settings, WiFi settings, NFC, Battery optimization settings, Display setting, sound settings by just one button click using flutter app_settings package in your flutter project.

Video Tutorial on App Settings flutter plugin


Getting Started

App_Settings flutter package Installation

In your flutter project, open pubspec.yaml file and under dependencies section you need to add app_settings flutter library

dependencies:
app_settings: ^4.1.1

after adding the library hit pub get button on pubspec.yaml file top right or else run command in IDE terminal ‘flutter pub get’

Import it

Once you have successfully added the required package to open flutter app settings, now you need to import app_settings.dart file.

import 'package:app_settings/app_settings.dart';

Platform Configuration

Android

You can directly use system settings screen like: WIFI Settings, Security, Device Setting, date Setting etc, but in some cases, to access bluetooth setting page or Location settings page, you need to add access permission in your AndroidManifest.xml file

android/app/src/main/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.yourname.yourapp">   

	 <uses-permission android:name="android.permission.BLUETOOTH" />  
	 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />  
	 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>  

 <application

iOS

TIP: If using Objective-C for iOS in your project, you will need to add use_frameworks! to your Runner project podfile in order to use this Swift plugin:

- target 'Runner' do
    use_frameworks!

Flutter App_ Setting package usage

Below are code to directly open setting page such as eg: Bluetooth Settings

Flutter Open App Setting

ElevatedButton(onPressed: (){
              AppSettings.openAppSettings();
 }, child: Text('Open App Setting'))
flutter open app setting

Flutter Open WiFI Setting

 ElevatedButton(onPressed: (){
              AppSettings.openWIFISettings();
 }, child: Text('WIFI SETTING')),
flutter open wifi search page

Flutter Open Location Setting

    ElevatedButton(onPressed: (){
              AppSettings.openLocationSettings();
    }, child: Text('Location Settting')),
flutter open location setting

Flutter Open Bluetooth Settings

ElevatedButton(onPressed: (){
                    AppSettings.openBluetoothSettings();
}, child: Text('BlueTooth')),
flutter open bluetooth settings

Flutter Open Device Settings

ElevatedButton(onPressed: (){
              AppSettings.openDeviceSettings();
 }, child: Text('Device Setting')),
flutter open setting page

Flutter Open Notification Settings

ElevatedButton(onPressed: (){
              AppSettings.openNotificationSettings();
 }, child: Text('Notification Setting')),
flutter open notification settings

Flutter Open Battery Optimization Settings

ElevatedButton(onPressed: (){
              AppSettings.openBatteryOptimizationSettings();
}, child: Text('Battery Optimization Setting'))
flutter open battery setting

Flutter Open Internal Storage Settings

ElevatedButton(onPressed: (){
              AppSettings.openInternalStorageSettings();
 }, child: Text('Open Storage Setting'))
Flutter open internal storage