Home Blog Page 53

Flutter Hive NoSQL Database – Basic Example

0
flutter hive tutorial with example
flutter hive tutorial with example

Hi Guys, Welcome to Proto Coders Point.

In this Flutter Hive Tutorial, Will learn the basic of Hive Database in flutter and also perform CRUD Operations using HIVE DB.

What is Hive Database in flutter

  • A HIVE is a lightweight & fast key-value pair NoSQL Database used in flutter application to store data locally.
  • Hive is been developed using pure DART Language.
  • It stands out to be very fast to perform CRUD Operations(full form CREATE, READ, UPDATE, DELETE),
  • most important all the data saved in Flutter hive database is highly secured by using AES-256 encrypted method.
  • Hive is a NoSQL database, it can be used as best alternative of SQLite Database.

When to use hive database in flutter app?

Suppose you are building a flutter app that is fully offline, for Example: ToDo Note App, Where a user can store his daily todo notes in mobile app itself (local database).

To build Todo list app there is not need of online server database, all the app data we can store locally in mobile itself.

Here are some example where you can use HIVE NoSQL database:


I have Created a playlist on Flutter Hive Tutorial on my youtube channel. Check it out, In those Flutter Hive tutorial, I am going to cover all the above feature using HIVE DATABASE.


Let’s get started

Create a new flutter project in your android Studio IDE or any of your favourite IDE.

Installing Hive in flutter project

1. Add hive dependencies

To install hive into your flutter project, open pubspec.yaml file and under dependencies section add this 2 packages

dependencies:
  hive:
  hive_flutter:

Keep the version empty if you want to install latest version available, else specify the version that you want to use.

Then after added above dependencies, just hit pub get button or run flutter pub get command in your IDE terminal.

install hive in flutter

2. Import hive.dart and hive_flutter.dart

Once the package is been installed successfully, To use Hive in flutter you need to import them.

import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';

How to Implement Hive Database in flutter app

To use Hive in flutter, you need to initialize it

Initialization Hive Database

You need to Start/initialize hive before loading your flutter app content, so the best place to initialize hive is before runApp(…..), As show in below snippet code

void main() async{
  await Hive.initFlutter();   //init hive
  runApp(const MyApp());
}

Open Hive Box – A Data Box in HIVE

 Box box1 = await Hive.openBox('database1');

If we compare openBox with SQLITE database, it’s similar to table in SQL.

So as you know that hive is NoSQL database (non-relational), Here we simply opening a BOX and then add data into that box.


How to Store data in hive box

To store data in Hive Database, first of all we need to create a hive box, that we have already done as above.

let’s store some data in Hive box

There are 2 ways to store data in hive Box

First: Simply add data in box

We can add data using add() method the value will get added into the Hive box in index wise. Therefore we can read the get using it’s index id.

box.add('RAJAT PALANKAR'); 

This is how value been stored

Second: Storing data in hive using Key-Value pair

In Hive Box Data can be stored in key-value pair as below

hive database store data in key value pair
box1.put('name', 'proto coders point');
box1.put('myname', 'Rajat palankar');

This is how data get stored if you save it using key-value

{myname: Rajat palankar, name: proto coders point}

You can make use of it’s key to access the value


Reading Data from Hive Database

We can read data by using two methods getAt(index) and get(‘key’)

getAt(index): This will fetch the value from hive box which specified index Eg: getAt(0)

get(‘key’): This will fetch value from specified key Eg: get(‘myname’) with return : Rajat Palankar.

box.getAt(0);
print(box.get('name'));

Delete data from Hive db

1. Deleting data of specific key

box.delete('name');

2. Completely clear/erase all the data from HIVE BOX

Hive.box('database1').clear();

Real all the data from HIVE Box

box1.toMap()

Flutter Hive Database – Example – Source Code

main.dart

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';

void main() async{
 await Hive.initFlutter();
  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 HomePage(),
    );
  }
}

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

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

class _HomePageState extends State<HomePage> {

  late Box box1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    createBox();
  }

  void createBox() async{
    box1 = await Hive.openBox('database1');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            
            ElevatedButton(onPressed: (){
              box1.put('name', 'proto coders point');
              box1.put('myname', 'Rajat palankar');
              print('DATA ADDED');
            }, child: const Text("Add")),

            ElevatedButton(onPressed: () async{
              print(box1.get('myname'));
              print(box1.get('name'));
            }, child: const Text("Read")),

            ElevatedButton(onPressed: (){
              box1.put('name', 'RAJAT');
            }, child:const   Text("Update")),

            ElevatedButton(onPressed: (){
               box1.delete('name');
            }, child: const Text("Delete")),

            ElevatedButton(onPressed: (){
               print(box1.toMap());
            }, child: const Text("Read All Data")),


            ElevatedButton(onPressed: (){
              Hive.box('database1').clear();
            }, child: const  Text("Delete BOX")),
          ],
        ),
      ),
    );
  }
}

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