Home Blog Page 81

Text Recognition Using Firebase ML Kit – Text Recognition in Android.

0

Hi Guys, Welcome to Proto Coders Point, In this android tutorial we will build an application that can recognize text in image with Firebase ML Kit.

Introduction to Firebase Machine Learning(ML) Kit

Firebase ML Kit is an mobile SDK that helps you in building an android or iOS apps that can help developer to add Machine Learning feature into there mobile application, This ML Kit is very powerfull and very easy to use.

Whether you’re new to Machine Learning or you have experienced in ML, you can easily implement the ML functionality that you need that too in just few lines of firebase ML Codes.

So as the title says that we gonna build an simple application that can read text from a image and display it to use.

RESULT OF FINAL OUTPUT OF APPLICATION

firebase ml kit text recognition android example

Firebase ML Kit text Recognition

Let’s start this Firebase ML Kit Android Project to read text from image, Just follow the below Steps

Step 1: Create a new android project in android studio

ofcourse you need to create a new android project or you may just open any existing android project

File > New > New Project ( here select Empty Activity )

creating new project image

Hit Next Button

Then Give a Good name to your android project, In my case i have named it as “TextRecognitionMLFirebase” you may name it as per your choice

Then, Hit the Finish Button, your android project will get built in few minutes.

Step 2 : Connect your android app to firebase console

First you  need to be signedIn with Google Account in your android Studio.

Then, Go to Tools > Firebase  a Android Assistant will open a side window from where you can connect your app to firebase console. Here select Analytics

firebase analytic

connect to firebase

In place of Connected in above image you may see Connect to Firebase Button, Click on it and it will open a default Browser so that you can connect android application to firebase console, Then In browser you need to follow some steps

 1: Add project

Now, on your browser with Firebase website opened click on Add Project

This page will get Loaded

adding android project to firebase console
Project Name will automatically get here you just need to hit Continue button

2: Config Google Analysis

adding android project to firebase console configuration google analysis

Here you need to accept all the terms and conditions of firebase console & then Hit Create Project.

Therefore your android studio project is successfully connected  to Firebase Console

firebase project is connected to android project

Now, Come back to Android Studio IDE.

Step 3 : Add Firebase Dependencies

Add Firebase ml vision and firebase core dependencies into yor android studio project.

Open built.gradle(Module:app)  then in dependencies section just add below Implementation code

implementation 'com.google.firebase:firebase-core:15.0.2'

implementation 'com.google.firebase:firebase-ml-vision:15.0.0'

Step 4 : Adding Camera Feature

Open Androidmanifest.xml and add the following required camera Feature permission

<uses-feature android:name="android.hardware.camera" android:required="true"/>

Step 5 : XML UI Design

Now it’s time to work with some UI Design for Text Recognition in android

open activity_main.xml  and add the below lines of XML code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

 <ImageView
     android:id="@+id/imageview1"
     android:layout_gravity="center"
     android:layout_width="match_parent"
     android:layout_height="400dp"
     />

    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:textSize="20dp"
        android:text="Display the text from the image"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/captureImage"
        android:text="Capture Image"
        />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/detectText"
        android:text="Detect Text"/>
</LinearLayout>

Above xml code has :

ImageView to display image captured by camera.

TextView to display text read by Firebase ML Kit.

Button 1 to Open Camera to capture image from camera

Button 2 to read or detect text from captured image.

Step 6 : Java Coding for firebase ML Kit Text Recognition

Open MainActivity.java  and copy paste below code

package com.example.textrecognitionmlfirebase;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextDetector;
import java.io.ByteArrayOutputStream;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    Button captureImage,DetectText;
    ImageView imageView1;
    TextView text1;
    static  final int REQUEST_IMAGE_CAPTURE = 1;
    Bitmap imageBitmap;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // initialization of Views
        captureImage = (Button)findViewById(R.id.captureImage);
        imageView1 = (ImageView)findViewById(R.id.imageview1);
        DetectText = (Button)findViewById(R.id.detectText);
        text1 = (TextView)findViewById(R.id.text1);

        //on button click open camera to capture image
        captureImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if(takePictureIntent.resolveActivity(getPackageManager())!=null){
                    startActivityForResult(takePictureIntent,REQUEST_IMAGE_CAPTURE);
                }
            }
        });

        //on click read the text from captured image
        DetectText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DetectTextFromImage();
            }
        });
    }

    private void DetectTextFromImage() {
        //read bitmap image
        FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(imageBitmap);
        //text detector from selected image 
        FirebaseVisionTextDetector textDetector = FirebaseVision.getInstance().getVisionTextDetector();

        textDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
            @Override
            public void onSuccess(FirebaseVisionText firebaseVisionText) {

                List<FirebaseVisionText.Block> blockList = firebaseVisionText.getBlocks();
                if(blockList.size()==0){
                    Toast.makeText(MainActivity.this,"No Text Found no images",Toast.LENGTH_LONG).show();
                }
                else{
                    for(FirebaseVisionText.Block block : firebaseVisionText.getBlocks())
                    {
                        String text = block.getText();
                        //set text to textview 
                        // that is been read from imagebitmap
                        text1.setText(text);
                    }
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(MainActivity.this,"Something Went Wrong",Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bundle extras  = data.getExtras();
        imageBitmap = (Bitmap) extras.get("data");

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        // camera captured image set to ImageView
        imageView1.setImageBitmap(imageBitmap);
    }
}

And there you go your app is ready to recognize text in image with ML Kit on android application.

Scratch Card like google pay reward card in android studio

0
Scratch card like google pay reward card in android application

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will implement Scratch Card in android studio,  an android app same like Google Pay(Tez app) reward scratch card in our android application.

I found the Source code in GitHub developed by Shubham Mahalkar, Credit to him

Result of the Final built app

scratch card reward google pay android studio

Scratch Card like google pay reward card in android studio

Step 1 : Create a new android project in android studio

offcourse you need to create a new android project or open any of your existing android project where you want to add Scratch card reward.

Give a name to your android project as “Scratch Card Google Pay” or anything as per you choice.

Step 2 : create a attrs xml file in values folder

go to res->values-> and create new file name it as attrs.xml

then copy paste below lines of code

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="ScratchCard">
        <attr
            name="scratchDrawable"
            format="reference|color" />
        <attr
            name="scratchWidth"
            format="dimension" />
    </declare-styleable>

</resources>

Step 3 : Create a java class ScratchCard.java

This class is used to create Graphical objects in xml layout. Even this class will keep track of any event happens such as user scratch the card to check his reward points.

We will implement this class in xml file to display a square box which we will be able to check the google pay reward point after the card is been scratched.

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

class ScratchCard extends View {
    private Drawable mDrawable;
    private float mScratchWidth;
    private Bitmap mBitmap;
    private Canvas mCanvas;
    private Path mPath;
    private Paint mInnerPaint;
    private Paint mOuterPaint;
    private OnScratchListener mListener;

    public interface OnScratchListener {
        void onScratch(ScratchCard scratchCard, float visiblePercent);
    }

    public ScratchCard(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        resolveAttr(context, attrs);
    }

    public ScratchCard(Context context, AttributeSet attrs) {
        super(context, attrs);
        resolveAttr(context, attrs);
    }

    public ScratchCard(Context context) {
        super(context);
        resolveAttr(context, null);
    }

    private void resolveAttr(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ScratchCard);
        mDrawable = typedArray.getDrawable(R.styleable.ScratchCard_scratchDrawable);
        mScratchWidth = typedArray.getDimension(R.styleable.ScratchCard_scratchWidth, Utils.dipToPx(context, 70));
        typedArray.recycle();
    }

    public void setOnScratchListener(OnScratchListener listener) {
        mListener = listener;
    }

    @Override
    protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
        super.onSizeChanged(width, height, oldWidth, oldHeight);

        if (mBitmap != null)
            mBitmap.recycle();

        mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);

        if (mDrawable != null) {
            mDrawable.setBounds(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
            mDrawable.draw(mCanvas);
        } else {
            mCanvas.drawColor(0xFFEC7063);
        }

        if (mPath == null) {
            mPath = new Path();
        }

        if (mInnerPaint == null) {
            mInnerPaint = new Paint();
            mInnerPaint.setAntiAlias(true);
            mInnerPaint.setDither(true);
            mInnerPaint.setStyle(Paint.Style.STROKE);
            mInnerPaint.setFilterBitmap(true);
            mInnerPaint.setStrokeJoin(Paint.Join.ROUND);
            mInnerPaint.setStrokeCap(Paint.Cap.ROUND);
            mInnerPaint.setStrokeWidth(mScratchWidth);
            mInnerPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        }

        if (mOuterPaint == null) {
            mOuterPaint = new Paint();
        }
    }

    private float mLastTouchX;
    private float mLastTouchY;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float currentTouchX = event.getX();
        float currentTouchY = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPath.reset();
                mPath.moveTo(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                float dx = Math.abs(currentTouchX - mLastTouchX);
                float dy = Math.abs(currentTouchY - mLastTouchY);
                if (dx >= 4 || dy >= 4) {
                    float x1 = mLastTouchX;
                    float y1 = mLastTouchY;
                    float x2 = (currentTouchX + mLastTouchX) / 2;
                    float y2 = (currentTouchY + mLastTouchY) / 2;
                    mPath.quadTo(x1, y1, x2, y2);
                }
                break;
            case MotionEvent.ACTION_UP:
                mPath.lineTo(currentTouchX, currentTouchY);
                if (mListener != null) {
                    int width = mBitmap.getWidth();
                    int height = mBitmap.getHeight();
                    int total = width * height;
                    int count = 0;
                    for (int i = 0; i < width; i += 3) {
                        for (int j = 0; j < height; j += 3) {
                            if (mBitmap.getPixel(i, j) == 0x00000000)
                                count++;
                        }
                    }
                    mListener.onScratch(this, ((float) count) / total * 9);
                }
                break;
        }

        mCanvas.drawPath(mPath, mInnerPaint);
        mLastTouchX = currentTouchX;
        mLastTouchY = currentTouchY;

        invalidate();
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(mBitmap, 0, 0, mOuterPaint);
        super.onDraw(canvas);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mBitmap != null) {
            mBitmap.recycle();
            mBitmap = null;
        }
    }
}

STEP 4 : Create a new Utils.java file

Utils.java this class will help you randomly generate as number from 1 – 100 and we will be able to display in a form of rewards point some like google Play app.

Utils.java

import android.content.Context;

import java.util.Random;

public class Utils {
    static Random random = new Random();

    public static float dipToPx(Context context, float dipValue) {
        float density = context.getResources().getDisplayMetrics().density;
        return dipValue * density;
    }


    //Generate random number(Prize)
    private static String generateCodePart(int min, int max) {
        int minNumber = 1;
        int maxNumber = 100;
        return String.valueOf((random.nextInt((maxNumber - minNumber) + 1) + minNumber));
    }

    public static String generateNewCode() {
        String firstCodePart = generateCodePart(1000, 9999);
        return "You Won\nRs." + firstCodePart;
    }
}

Step 5: Now Open activity_main.xml file and add the below lines of code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <View
        android:id="@+id/view"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_gravity="center"
        android:background="@color/colorPrimaryDark"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_gravity="center"
            android:background="@drawable/ic_launcher_background" />

        <TextView
            android:id="@+id/codeTxt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:gravity="center"
            android:textColor="@android:color/white"
            android:textSize="30sp" />

    </LinearLayout>

    <com.example.androidscratchcard.ScratchCard
        android:id="@+id/scratchCard"
        android:layout_width="300dp"
        android:layout_height="300dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnScratchAgain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="scratch again to get reward"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view" />

</androidx.constraintlayout.widget.ConstraintLayout>

” you just need to replace with package name with your android project package name” as shown below

scratchcard android studio

Step 6 : The Final Step add code in MainActivity.java

Then Now open MainActivity.java and add the below lines of code

package com.example.androidscratchcard;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private ScratchCard mScratchCard;
    TextView codeTxt;
    String number;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mScratchCard = findViewById(R.id.scratchCard);
        codeTxt = findViewById(R.id.codeTxt);
        number = codeTxt.getText().toString();
        codeTxt.setText(number);
        codeTxt.setText(Utils.generateNewCode());

        findViewById(R.id.btnScratchAgain).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                startActivity(getIntent());
            }
        });
    }

    private void scratch(boolean isScratched) {
        if (isScratched) {
            mScratchCard.setVisibility(View.INVISIBLE);
        } else {
            mScratchCard.setVisibility(View.VISIBLE);
        }
    }

    private void handleListeners() {
        mScratchCard.setOnScratchListener(new ScratchCard.OnScratchListener() {
            @Override
            public void onScratch(ScratchCard scratchCard, float visiblePercent) {
                if (visiblePercent > 0.8) {
                    scratch(true);
                }
            }
        });
    }
}

You are all set to run your application, Kindly feel free to ask questions in comments  section.

 

Automatically SMS OTP reading using Broadcast Receiver in android studio

1
Automatically SMS OTP reader using Broadcast Receiver in android studio
Automatically SMS OTP reader using Broadcast Receiver in android studio

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will build an android application that will be able in reading incoming message automatically in android to verify otp.

FINAL OUTPUT OF READING OTP AUTOMATICALLY

Automatically SMS OTP reader using Broadcast Receiver in android studio

Video Tutorial on How to auto read otp in android using Breadcast Receiver.

At the end of this android tutorial your app will be able the read sms and fetch all the text in that sms and then it will copy the OTP from SMS and paste it in EditText box.

So let’s begin implementation of otp sms reader

Create a new Android Project

Ofcourse you need to create a new android project or open any existing android project

To do so go to File > New > New Project

Give a name as per you need in my case i have names my application as “Auto sms otp reader”

Create a custom background for EditText and a Vector Image

1. edittextbackground.xml

create a new xml file in drawable folder

res > drawable(right click) > New > Drawable resource file

copy paste below xml code

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners android:radius="5dp"/>
    <solid android:color="#dcdcdc"/>

</shape>

2. Create a Vector Image

res > drawable (right click) > New > Vector Asset

a dialog box will appear on your screen as shown below

How to create Vector image asset on android studio

Then, Here you can select any kind of image clip Art.

Create a new Java Class names OTPReceiver

OTPReceiver.java

package com.example.autosmsotpreader;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.widget.EditText;

public class OTP_Receiver extends BroadcastReceiver {
    private  static EditText editText;

    public void setEditText(EditText editText)
    {
        OTP_Receiver.editText=editText;
    }

// OnReceive will keep trace when sms is been received in mobile
    @Override
    public void onReceive(Context context, Intent intent) {
        //message will be holding complete sms that is received
        SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent); 

        for(SmsMessage sms : messages)
        {
  
            String msg = sms.getMessageBody();
            // here we are spliting the sms using " : " symbol
            String otp = msg.split(": ")[1]; 

            editText.setText(otp);
        }

    }
}

eg: sms received is Your OTP is : 4587, Then in above code i have split the complete message string in to 2 parts using “:” this special symbol.

Open AndroidManifest.xml file & add the uses permission

adding uses permission

add this 4 user-permission inside <manifest>  here </manifest> tags

<!-- this are the permission need so that application can read sms -->
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.READ_PHONE_NUMBERS"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.WRITE_SMS"/>

Now, Add the following receiver OTPReceiver.java in manifest under <application> tag

<receiver android:name=".OTP_Receiver">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
</receiver>

as shown in the below screenshot

adding permission in android manifest xml

MainActivity.java

Copy paste the below lines of code in MainActivity.java

package com.example.autosmsotpreader;


import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


public class MainActivity extends AppCompatActivity {

    EditText otpnumber;
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //we need to ask user permission to auto read sms
        requestsmspermission();
        otpnumber = (EditText)findViewById(R.id.edittext);

        new OTP_Receiver().setEditText(otpnumber);
    }

  
    private void requestsmspermission() {
        String smspermission = Manifest.permission.RECEIVE_SMS;
        int grant = ContextCompat.checkSelfPermission(this,smspermission);

        //check if read SMS permission is granted or not
        if(grant!= PackageManager.PERMISSION_GRANTED)
        {
            String[] permission_list = new String[1];
            permission_list[0]=smspermission;

            ActivityCompat.requestPermissions(this,permission_list,1);
        }
    }


}

Recommended Android Articles

otp verification in android

textlocal api to send sms/otp verification

android check internet connection continuously

Loading Content Shimmer Effect in Flutter App Development Tutorial

0

Hi Guys, Welcome to Proto Coder Point, In this Flutter Tutorial will use Shimmer Effect flutter library to show/display loading content effect before showing the actual data.

To achieve this we will make use of Flutter Package Called shimmer

Learn more about this Library from Official site

What is Shimmer Effect ?

A Shimmer Effect is just an shine effect on any of the View like text, images or any widget.

Shimmer is one of the flutter package library that is one of the easiest way to add an shimmer effect to any widget in flutter.

Now a day it is mostly used as loading indicator, i,e is to show loading content effect.

Video Tutorial

FINAL OUTPUT

Flutter Shimmer Effect library gif image example

Ok let’s begin adding the Library in our flutter project

Step 1: Create a new Flutter Project

I am making use of android studio as my IDE to build Flutter Application

Create new Flutter project > Give a name as “Flutter Shimmer Effect”

or if you already have existing flutter project then just open it.

Step 2: Add the Required Dependencies

On the Left side you may see project section navigate towords it and just open pubspec.yaml file  and add the following shimmer library dependencies as show below

dependencies:
  shimmer: ^1.1.1    #library for Shimmer effect

after adding the dependencies you need to click on “pub get”,what this does is, it will download all the required package class file into your flutter project.

Step 3: Import the shimmer.dart package

Once you have added the dependencies in your project now ou can easily use those library classes just by importing the shimmer.dart file, wherever required.

import 'package:shimmer/shimmer.dart';

Snippet code how to use shimmer widget in flutter

SizedBox(
                    width: MediaQuery.of(context).size.width,
                    height: 400.0,
                    child: Shimmer.fromColors(
                      child: Card(
                        color: Colors.grey,
                      ),
                      baseColor: Colors.white70,
                      highlightColor: Colors.grey[700],
                      direction: ShimmerDirection.ltr,
                    ),
),

Output of above snippet code

flutter shimmer gif image

In above Snippet code i have made a sized box with width as screen size available using MediaQuery to get Screen size and Height of box manually specified as 400.0 px

we have some properties that can we used to show shimmer effect:

baseColor: which you can assume as a background color of shimmer effect

highlightColor : which will show you shimmer animation effect, some thing like it is loading content from internet.

direction : you can change the direction of the shimmer highlight color from left to right (ltr) , right to left (rtf), top to bottom (ttb) or bottom to top (btt) , to do so you just need to pass ShimmerDirection with specified direction.

Complete Source code of Flutter Shimmer Effect with loading a image after 5 seconds using Future.delayed function

main.dart

Copy paste the below linked of flutter dart code in main.dart file

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shimmer/shimmer.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool showImageWidget = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // create a future delayed function that will change showInagewidget to true after 5 seconds

    Future.delayed(const Duration(seconds: 5), () {
      setState(() {
        showImageWidget = true;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Shimmer Effect Example"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: <Widget>[
            //if show image widget is true then image will be displayed
            // is show image widgte is false then loading shimmer effect will be show for 5 seconds
            showImageWidget
                ? Image.network(
                    "https://i.pinimg.com/564x/1b/30/80/1b30806bed30a7d071752948d00e75f8.jpg",
                    width: MediaQuery.of(context).size.width,
                    height: 400.0,
                    fit: BoxFit.fill,
                  )
                : SizedBox(
                    width: MediaQuery.of(context).size.width,
                    height: 400.0,
                    child: Shimmer.fromColors(
                      child: Card(
                        color: Colors.grey,
                      ),
                      baseColor: Colors.white70,
                      highlightColor: Colors.grey[700],
                      direction: ShimmerDirection.ltr,
                    )),
            Text(
              "Shimmer Effect Example in flutter using Shimmer Flutter Library",
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 20),
            )
          ],
        ),
      ),
    );
  }
}

This Code is just for demo purpose

Here i have set a boolean value for showImageWidget = false

then, i have used a Future.delayed() function that will wait for 5 seconds then change showImageWidget = true,

So when showImageWidget  is false app will display shimmer loading effect and when showImageWidget becomes true after 5 second Image widget will be loaded on screen.

Flutter UI/UX Animated Curved Navigation Bar Library – Flutter Examples

0
Animated bottom navigation bar in flutter
Animated bottom navigation bar in flutter

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial example we will create a Bottom Navigation Bar by using Curved Navigation Bar Library.

Introduction to Curved Bottom Navigation bar Flutter Library

By using this flutter package library you can easily create a Home Page/MainPage with Animated Bottom Navigation bar, This Flutter UI Library is very easy to implementation of curved navigation bar.

DEMO ON FINAL RESULT OF THIS FLUTTER TUTORIAL

curved navigation bar flutter example

Adding this Curved Bottom Navigation bar library in our flutter Project

Step 1: Adding the Dependencies

dependencies:
  curved_navigation_bar: ^0.3.2 #latest version

Once, you add the dependencies you need to click on pub get button/text, What it does is it download all the required classes or library in you flutter project.

Step 2: Importing the library wherever required to use

import 'package:curved_navigation_bar/curved_navigation_bar.dart';

for example: if you want to add curved bottom navigation bar in main page of your flutter application, then open main.dart file and add the import package line on top.

Snippet code of how to use this library

Scaffold(
  bottomNavigationBar: CurvedNavigationBar(
    backgroundColor: Colors.blueAccent,
    items: <Widget>[
      Icon(Icons.add, size: 30),
      Icon(Icons.list, size: 30),
      Icon(Icons.compare_arrows, size: 30),
    ],
    onTap: (index) {
      //Handle button tap
    },
  ),
  body: Container(color: Colors.blueAccent),
)

In Scaffold widget, we have an option to add bottomNavigationBar where you can add your own custom Navigation bar or any of the ready name library.

Different Customizable Attributes of this Library

items : This accepts any kind of widgets. for eg : Icons in our case

index : can be used to change current navigation bar  or to set initial index when the app starts

color: to set Color of the bar, by default colors is been set to white.

buttonBackgroundColor: used to color of floating button on the bar. default is white.

backgroundColor : this color will be visible to the active bar or index.

onTap: trigger when used want to change the page or want to see any other contents.

animationCurve: Curves interpolating button change animation, default Curves.easeOutCubic, There are many more Curves animation you many like to use.

for more Curvers animation transaction effect visit here

animationDuration: Duration of button change animation, default Duration(milliseconds: 600).

height: Height of NavigationBar, min 0.0, max 75.0.

Then, thus we have learned more about this library.

Flutter Animated Bottom Navigation bar – Complete Code Flutter Examples

Create a new Flutter Project and add the dependencies in pubspec.yaml file as described in above Steps

Then, create 3 new dart pages

  1. HomePage.dart
  2. WorkPage.dart
  3. IdeaPage.dart

No need to give same name, you can name it as per you choice,

To create those pages follow this steps:

(Right Click) Lib > New > Dart File 

Creating new dart file in flutter android studio

Give a name to the dart file 

give a name to the dart file

Then add the following flutter dart code into those dart files.

HomePage.dart

import 'package:flutter/material.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.orange,
      body: Center(
        child: Container(
          child: Text(
            "THIS IS HOME PAGE",
            style: TextStyle(
                color: Colors.white,
                fontSize: 20,
                fontStyle: FontStyle.italic,
                fontWeight: FontWeight.w700),
          ),
        ),
      ),
    );
  }
}

WorkPage.dart

import 'package:flutter/material.dart';

class WorkPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.pink,
      body: Center(
        child: Container(
          child: Text(
            "THIS IS WORK PAGE",
            style: TextStyle(
                color: Colors.white,
                fontSize: 20,
                fontStyle: FontStyle.italic,
                fontWeight: FontWeight.w700),
          ),
        ),
      ),
    );
  }
}

IdeaPage.dart

import 'package:flutter/material.dart';

class IdeaPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.greenAccent,
      body: Center(
        child: Container(
          child: Text(
            "THIS IS IDEA PAGE",
            style: TextStyle(
                color: Colors.white,
                fontSize: 20,
                fontStyle: FontStyle.italic,
                fontWeight: FontWeight.w700),
          ),
        ),
      ),
    );
  }
}

The above 3 pages will get replaced/displayed when uses click or Tap on any of the Bottom Navigation bar.

Final the main page where all the activity happens

main.dart

import 'package:curved_navigation_bar/curved_navigation_bar.dart';
import 'package:curvedbottomnavbar/HomePage.dart';
import 'package:curvedbottomnavbar/IdeaPage.dart';
import 'package:curvedbottomnavbar/WorkPage.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Curved Novigation Bar',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  
  int selectedpage = 0; //initial value 
  
  final _pageOptions = [HomePage(), WorkPage(), IdeaPage()]; // listing of all 3 pages index wise
  
  final bgcolor = [Colors.orange, Colors.pink, Colors.greenAccent];  // changing color as per active index value
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _pageOptions[selectedpage], // initial value is 0 so HomePage will be shown 
      bottomNavigationBar: CurvedNavigationBar(
        height: 50, 
        buttonBackgroundColor: Colors.blueAccent,
        backgroundColor: bgcolor[selectedpage],
        color: Colors.white,
        animationCurve: Curves.linearToEaseOut,
        items: <Widget>[
          Icon(
            Icons.home,
            size: 30,
            color: Colors.black,
          ),
          Icon(
            Icons.work,
            size: 30,
            color: Colors.black,
          ),
          Icon(
            Icons.wb_incandescent,
            size: 30,
            color: Colors.black,
          )
        ],
        onTap: (index) {
          setState(() {
            selectedpage = index;  // changing selected page as per bar index selected by the user
          });
        },
      ),
    );
  }
}

How to check if internet is connected in Flutter? | Flutter Connectivity

0
Flutter connectivity - how to check if mobile is connected to internet or no
Flutter connectivity - how to check if mobile is connected to internet or no

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna see how to check if Internet is Connected in flutter using Flutter Connectivity Library. And if the Internet is Connect then whether it is using Mobile data or is in Wifi Connection. how to check internet connection continuously in flutter.

To study more about Connectivity Library in Flutter then visit here 

Introduction to  Flutter Connectivity Library

This Plugin is very useful if your app need internet connection to run the application perfectly, This Library allows your flutter Application to Discover Network Connectivity. This Flutter Library will also check if your  mobile is currently using cellular mobile data  or is using WiFi Connection.

This Flutter Plugin Perfectly works for Both Android and iOS devices, So it is been rated with 100 points in Flutter Library Store.

Final Output screen of this project

VIDEO TUTORIAL ON FLUTTER CHECK INTERNET CONNECTION

Then, let’s Start with adding this library into our Flutter Project.

Step 1: Adding Dependencies

Open pubspec.yaml file and add the following dependencies

dependencies:
  connectivity: ^0.4.8+2  // add this line

After adding the dependencies just hit Pub Get, This will download all the required packages of Flutter Connectivity library into your flutter project.

Step 2 : Import the Class plackage

Then, After adding the dependencies just you need to do is import the class package wherever it’s required.

import 'package:connectivity/connectivity.dart';

Step 3 : Snippet code How to use function or method from connectivity library

How to detect internet connection in flutter.

if internet connected, then Weather it mobile Data or Wifi Connection.

var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.none) {
  // Mobile is not Connected to Internet
}
else if (connectivityResult == ConnectivityResult.mobile) {
  // I am connected to a mobile network.
}

 else if (connectivityResult == ConnectivityResult.wifi) {
  // I am connected to a wifi network.
}

If mobile connectivity is  Wifi then, This is How to get Wifi details in flutter.

var wifiBSSID = await (Connectivity().getWifiBSSID());
var wifiIP = await (Connectivity().getWifiIP());network
var wifiName = await (Connectivity().getWifiName());wifi network

You can Also keep checking OnConnectivityChanged Like this :

@override
initState() {
  super.initState();

  subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
    // Got a new connectivity status!
  })
}

// Be sure to cancel subscription after you are done
@override
dispose() {
  super.dispose();

  subscription.cancel();
}

Complete Source Code – How to check if internet is connected in Flutter?

main.dart

Copy Paste Below Lines of Flutter Code in main.dart file

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

void main() => runApp(MyApp());

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

class HomeConnect extends StatefulWidget {
  @override
  _HomeConnectState createState() => _HomeConnectState();
}

class _HomeConnectState extends State<HomeConnect> {
  var wifiBSSID;
  var wifiIP;
  var wifiName;
  bool iswificonnected = false;
  bool isInternetOn = true;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    GetConnect(); // calls getconnect method to check which type if connection it 
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Connectivity..."),
      ),
      body: isInternetOn
          ? iswificonnected ? ShowWifi() : ShowMobile()
          : buildAlertDialog(),
    );
  }

  AlertDialog buildAlertDialog() {
    return AlertDialog(
      title: Text(
        "You are not Connected to Internet",
        style: TextStyle(fontStyle: FontStyle.italic),
      ),
    );
  }

  Center ShowWifi() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
              " Your are connected to ${iswificonnected ? "WIFI" : "MOBILE DATA"}"),
          Text(iswificonnected ? "$wifiBSSID" : "Not Wifi"),
          Text("$wifiIP"),
          Text("$wifiName")
        ],
      ),
    );
  }

  Center ShowMobile() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(" Your are Connected to  MOBILE DATA"),
        ],
      ),
    );
  }

  void GetConnect() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.none) {
      setState(() {
        isInternetOn = false;
      });
    } else if (connectivityResult == ConnectivityResult.mobile) {
     
      iswificonnected = false;
    } else if (connectivityResult == ConnectivityResult.wifi) {
      
      iswificonnected = true;
      setState(() async {
        wifiBSSID = await (Connectivity().getWifiBSSID());
        wifiIP = await (Connectivity().getWifiIP());
        wifiName = await (Connectivity().getWifiName());
      });

   
    }
  }
}

 

Recommended Tech Articles

android check internet connection continuously

fetching data in flutter and displaying in listview – http example

android php mysql login