Home Blog Page 80

Flutter : Auto Create Model from JSON file | json model Dart Package

0

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial, we will learn how to auto create model class from json file by making use of json model dart package library.

What is Json Model package?

Flutter json model package library is been used to create a model class from a json file. In other words this Library will help you to convert json data to model class for your flutter application.

Ok so let’s begin

Flutter : Auto Create Model from JSON file | json model Dart Package

Step 1 : Add Required Dependencies

Create a new Flutter project and add the following 4 dependencies.

To do so open pubspec.yaml file and add those.

dependencies

json_annotation : to create code for JSON serialization and deserialization.

dev_dependencies 

json_model: used to generate model

build_runner: concrete way of generating files using dart code.

json_serializable: helps provider builder for handling JSON request.

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.3
  json_annotation:  #to create code for JSON serialization and deserialization.

dev_dependencies:
  flutter_test:
    sdk: flutter

  json_model:  #used to generate json to model
  build_runner: ^1.0.0 #concrete way of generating files using Dart code
  json_serializable: ^2.0.0  #helps provides builder for handling JSON

JSON to Model class can be generated simple by using json_model but json model will also make use of json serializable for Mapping and all other Modeling Staff.

So just add the above 4 dependencies in your flutter project pubspec.yaml file.

Step 2 : Create folder and Create .json file

Then, after adding json model and other 3 dependencies, now you need to create a new folder by name “jsons” and inside that folder create a .json file and add some json data in it.

  1. Create a “jsons” directory in root of your flutter project.
  2. Create a json file under jsons directory.
  3. Add below json data in that json file.

json data for model

{
  "name": "Flash",
  "power": "Speed Run : His connection to the Speed Force gives him plenty of abilities.",
  "url": "https://m.media-amazon.com/images/M/MVXSDS_.jpg"
}

Check out my project structure in below image

json to model flutter
Created a folder by name “jsons” and inside it created a .json file which has some json data in it

Step 3 : Go to Terminal  and Run the Flutter Command

Once, you have created .json file and some json data in it, Now open your terminal and run the below Flutter Command

flutter packages pub run json_model

as shown below

flutter cmd to run json model

What this command will do is, It will auto detect json file from jsons  directory and create model from json data into your flutter project as shown below

"flutter

Conclusion

Ok so in this tutorial we checked out how to auto-generate data model class from JSON file by using JSON MODEL dart package library.

Recommended Post 

fetching data in flutter and displaying in listview

Install nodejs latest version on Ubuntu & Windows in 2 mins

1
Installing Nodejs On Ubuntu & Windows

Hi Guys, Welcome to Proto Coders Point, In this Programmer Blog post we will learn About What is Node.js and Why is Node js used for? and even we will check how to install NODE.JS on Ubuntu & Windows OS.

What is Node.js?

Node.js is basically an Open-Source Scripting Language, It is and JavaScript runtime Environment that executes JS codes outside a browser also.

The Node js will help the Back-End Developer use javascript to write server-side script to produce dynamic web page and fetch data from database before web page is sent to user’s browers.

In Short Node.js is and Open Source server environment which is completely free to used and Node.js is very speed and easily compatible on various OS platforms (Windows, Linus , Unix, Mac OS any many more)

Why NodeJS is Famous?

By using Simple JavaScript, we cannot get access to files system from browser but sometimes there is a situation, where we need to be able to read data from local file system sinse this is not possible by using Javascript.

In this sense we need something that we can use to interact directly with the computer file system, that’s what exactly what node.js allows us to do.

Node.js allows us to take javascript out of the browser by allowing us to interact directly with the computer data source.

Thus not we can access system files, Therefore by using Node.js we can also create a desktop application and Atom Editor is the best example that is built using Node.js.

Then, Now you can write javascript code not just for browser but also to make use of hardware component or file system.

Why node.js?

Well, node.js can be run on your own computer or somebody else computer rather say it you can run server script using Node.js on server computer.

How to Install nodejs latest version on ubuntu

Here we use curl to download nodejs 16 on Ubuntu.

Option 1: Using curl

Installation Steps

1. Install curl on ubuntu

sudo apt install curl

2. Download NodeJS 16 Repository

curl -sL https://deb.nodesource.com/setup_16.x | sudo bash –

curl -sL https://deb.nodesource.com/setup_16.x | sudo bash -

In above cmd just replace setup_16.x to latest Eg: setup_17.x (whichever is latest).

3. Finally install Latest NodeJS using below cmd.

sudo apt -y install nodejs

Finally we have successfully installed, Latest Nodejs On Ubuntu, just by following above 3 cmd both node & npm will get installed.

4. Check Node & npm version

node  -v
npm -

Option 2: use standard Binary Package to install nodeJS & Npm in ubuntu

1. use wget to download the nodeJS of your desired version, Note that in below command replace v16.17.1 with the version you want to download.

sudo wget https://nodejs.org/dist/v16.17.1/node-v16.17.1-linux-x64.tar.xz

2. to unpack or unzip the above tar.xz u need to xz-utils so install it.

sudo apt-get install xz-utils

3. Now extract the tar.xz using xz-utils as below, This cmd will install node.js binary in /usr/local/:

tar -C /usr/local --strip-components 1 -xJf node-v16.17.1-linux-x64.tar.xz

4. Finally Node and npm is been install in /usr/local/bin, To check run below commands

ls -l /usr/local/bin/node
ls -l /usr/local/bin/npm

or 

node -v
npm -v

How to Install Node.js on Windows

Installation Steps

  1. Download the Windows installer from the Nodes.js® web site
  2. Choose the LTS version that’s shown on the left. 
  3. Run the installer (the .msi file you downloaded in the previous step.)
  4. Follow the prompts in the installer (Accept the license agreement, click the NEXT button a bunch of times and accept the default installation settings).
node js installation
node js installation

5. Restart your computer. You won’t be able to run Node.js® until you restart your computer.

6. Confirm that Node has been installed successfully on your computer by opening a Hyper terminal and typing in the commands node --version

how to check nodejs version

You should see the version of node you just installed. So you can see my pc is been install with NodeJS version 12.17.0

Getting Started with NodeJS

Once Nodejs is been Installed successfully in your OS, Let’s use write a node script that will simply display ” HelloWorld” on the Browser.

Create a folder on your Desktop named “nodejs” under that folder Create a .js file named “helloworld.js”, and add the following code:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/h1'});
    res.end("Hello World! Welcome to Proto Coders Point");
}).listen(8080);

console.log(" Server Running at : http://localhost:8080/");

Save the file.

Then Open Comment Prompt and run the below command

1. moving inside folder.

C:\Users\rajat>cd Desktop

C:\Users\rajat\Desktop>cd nodejs2

2. run the script using node cmd

C:\Users\rajat\Desktop\nodejs2>node helloworld.js

Then,  your computer works as a server of helloworld.js file

If anyone tries to access your computer on port 8080, they will get a “Hello World!” message in return!

Start your internet browser, and type in the address: http://localhost:8080

how to run nodejs file in cmd prompt

Result on the browser

Password Validation regex in Android

0
Password Text Field Validation in android
Password Text Field Validation in android

Hi Guys Welcome to Proto Coders Point, In this Android Tutorial we will learn how to implement password validation regex requirements in android app.

In other words Password Validation   To check a password character must be minimum 8 character length which include alphebet, numeric digits and any special character symbol.

Password Validation requirements

  1. Atleast 8 character in length.
  2. Minimum One Uppercase.
  3. Minimum One Number.
  4. and should contain 1 Special Symbol.

Password Validation regex in android

Video Tutorial

Follow the below Steps and Code to integrate this validation textfield in android.

Step 1 : Create a new android project

offcourse you need to create a new Android Project or Open any existing project in android studio.

File > New > New Project > Empty Activity

Give a name to android project as “Password Validation android”  or anything else as per your choice.

hit next > finish.

Step 2 : Add Material Design Dependencies

Open build.gradle(app level) and add the below android design dependencies.

implementation 'com.android.support:design:29.0.0'

We are making use of android design library dependencies so that we can use material.textfield.TextInputLayout  and androidx.cardview.widget.CardView in our android UI design.

Step 3 : Creating a Registration page UI

Open activity_main.xml file and copy page the below xml UI code.

registration page UI design android
registration page UI design android

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView 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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="20dp"
        android:orientation="vertical"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="35sp"
            android:textStyle="bold"
            android:text="Register"
            android:textColor="@android:color/black"
            android:gravity="center"
            android:layout_marginBottom="30dp"
            />

        <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">

        <EditText
            android:id="@+id/etFullname"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:hint="Enter Full Name"
            android:inputType="text"
            android:textColor="@android:color/black"
            />

    </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="60dp"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">

            <EditText
                android:id="@+id/etEmail"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:hint="Enter Email"
                android:inputType="text"
                android:textColor="@android:color/black"
                />

        </com.google.android.material.textfield.TextInputLayout>



        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="60dp"
            app:passwordToggleEnabled="true"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">

            <EditText
                android:id="@+id/etPassword"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:hint="Enter Password"
                android:inputType="textPassword"
                android:textColor="@android:color/black"
                />

        </com.google.android.material.textfield.TextInputLayout>



        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Password must be "
            android:layout_marginTop="10dp"
            android:textColor="@android:color/black"
            android:textSize="18sp"
            />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:orientation="horizontal">

            <androidx.cardview.widget.CardView
                android:id="@+id/card1"
                android:layout_width="20dp"
                android:layout_height="20dp"
                app:cardBackgroundColor="#dcdcdc"
                app:cardCornerRadius="25dp"
                android:layout_gravity="center">

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


            </androidx.cardview.widget.CardView>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="@android:color/black"
                android:text="Atleast 8 character"
                android:gravity="center|start"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"

                android:layout_marginLeft="10dp" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:orientation="horizontal">

            <androidx.cardview.widget.CardView
                android:id="@+id/card2"
                android:layout_width="20dp"
                android:layout_height="20dp"
                app:cardBackgroundColor="#dcdcdc"
                app:cardCornerRadius="25dp"
                android:layout_gravity="center">

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


            </androidx.cardview.widget.CardView>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="@android:color/black"
                android:text="mininum one number"
                android:gravity="center|start"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"

                android:layout_marginLeft="10dp" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:orientation="horizontal">

            <androidx.cardview.widget.CardView
                android:id="@+id/card3"
                android:layout_width="20dp"
                android:layout_height="20dp"
                app:cardBackgroundColor="#dcdcdc"
                app:cardCornerRadius="25dp"
                android:layout_gravity="center">

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


            </androidx.cardview.widget.CardView>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="@android:color/black"
                android:text="minimum one uppercase"
                android:gravity="center|start"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"

                android:layout_marginLeft="10dp" />

        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:orientation="horizontal">

            <androidx.cardview.widget.CardView
                android:id="@+id/card4"
                android:layout_width="20dp"
                android:layout_height="20dp"
                app:cardBackgroundColor="#dcdcdc"
                app:cardCornerRadius="25dp"
                android:layout_gravity="center">

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


            </androidx.cardview.widget.CardView>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="@android:color/black"
                android:text="minimum one special symbol"
                android:gravity="center|start"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"

                android:layout_marginLeft="10dp" />

        </LinearLayout>

        <androidx.cardview.widget.CardView
            android:id="@+id/cardsignup"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_marginTop="20sp"
            app:cardBackgroundColor="#dcdcdc">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textSize="20sp"
                android:textStyle="bold"
                android:text="Sign Up"
                android:textColor="@android:color/black"
                android:gravity="center"/>

        </androidx.cardview.widget.CardView>


    </LinearLayout>

</androidx.core.widget.NestedScrollView>

As you can see in above Ui Screenshot we have 3 EditText, 4 Cardview with a tick Icon and a Button.

Step 4 : Java Coding to Handle password Validation

In Below Java code we have 2 method one to check passwordValidation() and other to keep track of InputChanged() in TextField.

MainActivity.java

package com.example.passwordcharactervalidation;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

public class MainActivity extends AppCompatActivity {

    EditText etfullname,etEmail,etPassword;

    CardView card1,card2,card3,card4,cardButtonSignUp;

    private  boolean is8char=false, hasUpper=false, hasnum=false, hasSpecialSymbol =false, isSignupClickable = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etfullname=(EditText) findViewById(R.id.etFullname);
        etEmail = (EditText)findViewById(R.id.etEmail);
        etPassword = (EditText)findViewById(R.id.etPassword);

        card1 = (CardView)findViewById(R.id.card1);
        card2 = (CardView)findViewById(R.id.card2);
        card3 = (CardView)findViewById(R.id.card3);
        card4 = (CardView)findViewById(R.id.card4);
        cardButtonSignUp = (CardView)findViewById(R.id.cardsignup);


        cardButtonSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        inputChanged();
    }

    @SuppressLint("ResourceType")
    private void passwordValidate(){
        String name = etfullname.getText().toString();
        String email = etEmail.getText().toString();
        String password = etPassword.getText().toString();


        if(name.isEmpty())
        {
            etfullname.setError("Please Enter Full name ");
        }

        if(email.isEmpty())
        {
            etEmail.setError("Please Enter Email ");
        }

        // 8 character
        if(password.length()>= 8)
        {
            is8char = true;
            card1.setCardBackgroundColor(Color.parseColor(getString(R.color.colorAccent)));
        }else{
            is8char = false;
            card1.setCardBackgroundColor(Color.parseColor(getString(R.color.colorGrey)));
        }

        //number
        if(password.matches("(.*[0-9].*)"))
        {
            hasnum = true;
            card2.setCardBackgroundColor(Color.parseColor(getString(R.color.colorAccent)));
        }else{
            hasUpper = false;
            card2.setCardBackgroundColor(Color.parseColor(getString(R.color.colorGrey)));
        }
        //upper case
        if(password.matches("(.*[A-Z].*)"))
        {
            hasUpper = true;
            card3.setCardBackgroundColor(Color.parseColor(getString(R.color.colorAccent)));
        }else{
            hasUpper = false;
            card3.setCardBackgroundColor(Color.parseColor(getString(R.color.colorGrey)));
        }

        //symbol
        if(password.matches("^(?=.*[_.()$&@]).*$")){
            hasSpecialSymbol = true;
            card4.setCardBackgroundColor(Color.parseColor(getString(R.color.colorAccent)));
        }else{
            hasSpecialSymbol = false;
            card4.setCardBackgroundColor(Color.parseColor(getString(R.color.colorGrey)));
        }
//
    }

    private  void inputChanged(){

        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @SuppressLint("ResourceType")
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                passwordValidate();
                if(is8char && hasnum && hasSpecialSymbol && hasUpper)
                {
                                      cardButtonSignUp.setCardBackgroundColor(Color.parseColor(getString(R.color.colorPrimary)));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
//
        });
//
    }
}

Final Output

android password field validation

 

How to Show Snackbar in Flutter

0
how to show snackbar in flutter

Hi Guys, Welcome to Proto Codes Point, In this flutter tutorial we check how to show snackbar in flutter app development.

What is Snackbar?

A Flutter Snackbar is Quick Information to the user of your application. Using material design snackbar you can give a quick message, error or warning message to the app user,

One of the best and the most useful way of showing message or notification is by using Flutter Material Snackbar.

Video Tutorial 

ScaffordMessenger – scaffold.of(context) error solution

How to Show Snackbar?

Step 1: Create a new Project

Of course, you need to create a new Flutter project in Android Studio or VSCode whichever is your favourite IDE.

Step2: Initialise a global key scaffold

Create a stateful class and declare a Global key scaffold state

final GlobalKey<ScaffoldState> _globalKey = GlobalKey<ScaffoldState>();

Step 3: Create a method of Snackbar bar

void _showSnackbar() {
   final snack = SnackBar(
     content: Text("This is Snackbar Example"),
     duration: Duration(seconds: 15),
     backgroundColor: Colors.green,
   );

   _globalKey.currentState.showSnackBar(snack);
  }

Step 4: Call the method to show snackbar

Then, ok to call the method _showSnackbar we will make use of the RaisedButton widget in a flutter, when it is been pressed the method is been called and this method will showSnackBar using scaffordState globalkey.

RaisedButton(
              onPressed: () {
                _showSnackbar();  // calling the method on pressed
              },
              child: Text("Click me"),
            
),

1st. Way using _globalKey.currentState – Show Snackbar in flutter App

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(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Snackbar(),
    );
  }
}

class Snackbar extends StatefulWidget {
  @override
  _SnackbarState createState() => _SnackbarState();
}

class _SnackbarState extends State<Snackbar> {

  final GlobalKey<ScaffoldState> _globalKey = GlobalKey<ScaffoldState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _globalKey,
      appBar: AppBar(title: Text("Flutter Snackbar Example"),),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("press to show Snackbar"),
            RaisedButton(
              onPressed: () {
                _showSnackbar();
              },
              child: Text("Click me"),
            )
          ],
        ),
      ),
    );
  }

  void _showSnackbar() {
   final snack = SnackBar(
     content: Text("This is Snackbar Example"),
     duration: Duration(seconds: 15),
     backgroundColor: Colors.green,
   );

   _globalKey.currentState.showSnackBar(snack);
  }
}







2nd. Way using ScaffoldMessenger.of(context).showSnackBar

Show Snackbar in flutter using ScaffoldMessenger.of(context).shotSnackbar(snackbar);

import 'package:flutter/cupertino.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 Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SnackBarExample(),
    );
  }
}

class SnackBarExample extends StatefulWidget {
  @override
  _SnackBarExampleState createState() => _SnackBarExampleState();
}

class _SnackBarExampleState extends State<SnackBarExample> {

  //creating an instance of Snackbar to use it in scaffoldMessenger
  final snackBar = SnackBar(content: Text('New Way to show snackbar'),duration: Duration(seconds:1 ),action: SnackBarAction(
    onPressed: (){

    }, label: 'Button',
  ),);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child:Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            EButton(),
            ElevatedButton(onPressed: (){
            // using ScaffoldMessenger
              ScaffoldMessenger.of(context).showSnackBar(snackBar);
            }, child: Text('New Snackbar')),
          ],
        ),
      ),
    );
  }
}

Conclusion

Yes, Flutter provides its own Snackbar, but the only drawable of default is it create lots of boilerplate code and is not as customizable, so making use of the Flutter Flushbar library will remove this drawable and you can easily style as per your creativity that too without any scaffold.

This library is useful when you want to show more than a simple message.

Flutter Snackbar Example | flushbar flutter Library

1
how to show snackbar in flutter

Hi Guys, Welcome to Proto Codes Point, In this flutter tutorial we check how to show snackbar with flutter app development.

What is Snackbar in mobile app?

A Flutter Snackbar is Quick Information to the user of your application. Using material design snackbar  you can give a quick message, error or warning message to the app user, One of the best and the most useful way of showing message is by using Flutter Material Snackbar.

But using Flutter default snackbars is not at all great now, This drawbacks of default snackbar we can solve with the use of Flutter Flushbar Library.

Flutter Flushbar plugin libray will work same like snackbars but the think is you can easily customize the snackbar as per you wish and it’s very much simple to use.

Flutter Flushbar library

After Creating a new Flutter project in your Favourite IDE platform like android studio or VSCode….

Adding dependencies

Then to add flushbar dependencies,

open pubspec.yaml file and all the following dependencies

dependencies:
  flushbar: ^1.10.4

then, after adding hit the Pub get (to download the library).

get latest version on official site here.

Import the package

Then import flushbar package wherever you need to display snackbar to show some information.

import 'package:flushbar/flushbar.dart';
import 'package:flushbar/flushbar_helper.dart';

Now start using flushbar widget

1. Simple Flushbar

This Simple Flushbar will displaybasically a copy of default Snackbar that by using Flushbar library,

To make it bit change i have added a simple click me button to it.

//Simple Flushbar with a button
void show_Simple_Flushbar(BuildContext context) {
  Flushbar(
    // There is also a messageText property for when you want to
    // use a Text widget and not just a simple String
    message: 'Hello from a Flushbar',
    // Even the button can be styled to your heart's content
    mainButton: FlatButton(
      child: Text(
        'Click Me',
        style: TextStyle(color: Theme.of(context).accentColor),
      ),
      onPressed: () { print("Simple snackbar example");},
    ),
    duration: Duration(seconds: 3),
    // Show it with a cascading operator
  )..show(context);

}

The above snippet code is just a method by calling with a button press will show snackbar to the user. To call the Function you can just make use of MaterialButton widget.

As you can check that there’s no Scaffold or any boilerplate code, and it’s very easy to make snackbar styleable.

Output of simple Flushbar

flutter snackbar example

Snackbar with Icons and more Information

Showing only Textual Info to user is not enough, Sometimes, we also need to show different kinds of information like warning, error message with some Icons on snackbar and Snackbar with different color, and thus it very easy to implement customized snackbar using Flushbar library.

void show_Title_n_message_Flushbar(BuildContext context) {
  Flushbar(
    title: 'Success',
    message: 'Form Submitted successfully',
    icon: Icon(
      Icons.done_outline,
      size: 28,
      color: Colors.green.shade300,
    ),
    leftBarIndicatorColor: Colors.blue.shade300,
    duration: Duration(seconds: 3),
  )..show(context);
}

snackbar with icons
A Flushbar with an icon and additional color

Fully Customized Flutter Snackbar

Showing Snackbar using Flushbar library does not end here at just showing information or any message. You can really make use of this Flutter Flushbar library to customize snackbar as per you creativity,

This library can be customized in a sense like maing it rounded border, giving gradient background to snackbar and also custom animation or shadow effect.

void show_Custom_Flushbar(BuildContext context) {
  Flushbar(
    duration: Duration(seconds: 3),
    margin: EdgeInsets.all(8),
    padding: EdgeInsets.all(10),
    borderRadius: 8,
    backgroundGradient: LinearGradient(
      colors: [Colors.green.shade800, Colors.greenAccent.shade700],
      stops: [0.6, 1],
    ),
    boxShadows: [
      BoxShadow(
        color: Colors.black45,
        offset: Offset(3, 3),
        blurRadius: 3,
      ),
    ],
    // All of the previous Flushbars could be dismissed by swiping down
    // now we want to swipe to the sides
    dismissDirection: FlushbarDismissDirection.HORIZONTAL,
    // The default curve is Curves.easeOut
    forwardAnimationCurve: Curves.fastLinearToSlowEaseIn,
    title: 'This is a floating Flushbar',
    message: 'Lorem ipsum dolor sit amet',
  )..show(context);
}

output

customized snackbar flutter

Customization doesn’t stop here, There are more properties of flushbar that you can use to modify snackbar.  Please visit official site to learn more about Flushbar library.

Complete Flutter Flushbar code

Copy paste below lines of code in main.dart file

main.dart

import 'package:flutter/material.dart';
import 'package:flushbar/flushbar.dart';
import 'package:flushbar/flushbar_helper.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 FlushBar Example ',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text("Flutter Snackbar Example - using Flushbar library",style: TextStyle(fontSize: 18,color: Colors.black,fontStyle: FontStyle.italic,decoration: TextDecoration.none),textAlign: TextAlign.center,),
            ),
            MaterialButton(
              child: Text("Simple",style: TextStyle(color: Colors.white),),
              color: Colors.orange,
              onPressed: (){
                show_Simple_Flushbar(context);
              },
            ),
            MaterialButton(
              child: Text("Text With Message n Icon",style: TextStyle(color: Colors.white),),
              color: Colors.blue,
              onPressed: (){
                show_Title_n_message_Flushbar(context);
              },
            ),
            MaterialButton(
              child: Text("Flush Bar Helper",style: TextStyle(color: Colors.white),),
              color: Colors.green,
              onPressed: (){
                show_FlushbarHelper(context);
              },
            ),
            MaterialButton(
              child: Text("Customized Flush bar",style: TextStyle(color: Colors.white),),
              color: Colors.green,
              onPressed: (){
                show_Custom_Flushbar(context);
              },
            ),
          ],
        ),
      ),
    );
  }
}

//Simple Flushbar with a button
void show_Simple_Flushbar(BuildContext context) {
  Flushbar(
    // There is also a messageText property for when you want to
    // use a Text widget and not just a simple String
    message: 'Hello from a Flushbar',
    // Even the button can be styled to your heart's content
    mainButton: FlatButton(
      child: Text(
        'Click Me',
        style: TextStyle(color: Theme.of(context).accentColor),
      ),
      onPressed: () {},
    ),
    duration: Duration(seconds: 3),
    // Show it with a cascading operator
  )..show(context);

}

void show_Title_n_message_Flushbar(BuildContext context) {
  Flushbar(
    title: 'Success',
    message: 'Form Submitted successfully',
    icon: Icon(
      Icons.done_outline,
      size: 28,
      color: Colors.green.shade300,
    ),
    leftBarIndicatorColor: Colors.blue.shade300,
    duration: Duration(seconds: 3),
  )..show(context);
}

void show_FlushbarHelper(BuildContext context) {
  FlushbarHelper.createInformation(
    title: 'Exit',
    message: 'Do you want to close the app ?',
  ).show(context);
}


void show_Custom_Flushbar(BuildContext context) {
  Flushbar(
    duration: Duration(seconds: 3),
    margin: EdgeInsets.all(8),
    padding: EdgeInsets.all(10),
    borderRadius: 8,
    backgroundGradient: LinearGradient(
      colors: [Colors.green.shade800, Colors.greenAccent.shade700],
      stops: [0.6, 1],
    ),
    boxShadows: [
      BoxShadow(
        color: Colors.black45,
        offset: Offset(3, 3),
        blurRadius: 3,
      ),
    ],
    // All of the previous Flushbars could be dismissed by swiping down
    // now we want to swipe to the sides
    dismissDirection: FlushbarDismissDirection.HORIZONTAL,
    // The default curve is Curves.easeOut
    forwardAnimationCurve: Curves.fastLinearToSlowEaseIn,
    title: 'This is a customized Snackar',
    message: 'Try it now ',
  )..show(context);
}

 

Conclusion

Yes Flutter provides its own Snackbar, but the only drawable of default is it create lots of boilerplate code and is not as per customizable, so making use of Flushbar library will remove this drawable and you can easily style as per you creativity that too without any scafford.

This library is useful when you want to show  more that a simple message.

 

How to check internet connection in android using Broadcast Receiver

0
How to check internet connection in android
How to check internet connection in android

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will create a demo on how to check the state of internet connection using android broadcast receiver.

How to Check Internet Connection in android using Broadcast Receiver

Step 1: Create a new Project in android studio

OffCourse you need to Create a new Project,

Go to File > New Project and then fill all the details like app name, android package name, etc and hit the finish button to create new android project.

Step 2: add Network state permission on AndroidManifest.xml

Now, Open AndroidManifest.xml file and ACCESS_NETWORK_STATE permission

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

Step 3: Create a customDialog xml layout

This customDialog will be shown to user when user android device is not connect to internet.

how to check internet connectivity in android

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:background="#024BFF"
    android:gravity="center"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:src="@drawable/no_internet"
        android:layout_gravity="center"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Ooops!"
        android:gravity="center"
        android:textColor="#FFF"
        android:textSize="40sp"/>

    <TextView
        android:id="@+id/nettext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="No Internet Connection found"
        android:textColor="#FFF"
        android:textSize="15sp"
        android:layout_marginBottom="10dp"
        android:gravity="center"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ON YOUR DATA AND HIT RESTART"
        android:textColor="#FFF"
        android:textSize="15sp"
        android:layout_marginBottom="10dp"
        android:gravity="center"/>

    <Button
        android:id="@+id/restartapp"
        android:layout_width="300dp"
        android:layout_height="50dp"
        android:text="Restart"
        android:textSize="20sp"
        android:background="@android:color/holo_green_light"/>

</LinearLayout>

Step 4: Create a new java class, NetworkUtil

Then, on the left Project section

app > java > your package name ( right click ) > New > Java Class

Create a NetworkUtil class to find the network status as show below.

NetworkUtil.java

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
class NetworkUtil {
    
    public static String getConnectivityStatusString(Context context) {
        String status = null;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null) {
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                status = "Wifi enabled";
                return status;
            } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                status = "Mobile data enabled";
                return status;
            }
        } else {
            status = "No internet is available";
            return status;
        }
        return status;
    }
}

Step 5 : Create a broadcast receiver class

This broadcart receiver in android will keep track of when internet is connected or disconnected by using which we can easily update UI updates to the users.

app > java > your package name ( right click ) > New > Java Class

MyReceiver.java

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class MyReceiver extends BroadcastReceiver {
    Dialog dialog;
    TextView nettext;
    
    @Override
    public void onReceive(final Context context, final Intent intent) {

        String status = NetworkUtil.getConnectivityStatusString(context);
        dialog = new Dialog(context,android.R.style.Theme_NoTitleBar_Fullscreen);
        dialog.setContentView(R.layout.customdialog);
        Button restartapp = (Button)dialog.findViewById(R.id.restartapp);
        nettext =(TextView)dialog.findViewById(R.id.nettext);
        
        restartapp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((Activity) context).finish();
                Log.d("clickedbutton","yes");
                Intent i = new Intent(context, MainActivity.class);
                context.startActivity(i);

            }
        });
        Log.d("network",status);
        if(status.isEmpty()||status.equals("No internet is available")||status.equals("No Internet Connection")) {
            status="No Internet Connection";
            dialog.show();
        }

        Toast.makeText(context, status, Toast.LENGTH_LONG).show();
    }
}

Step 6 : update broadcast receiver in androidmanifest.xml

Then you need to update the broadcast receiver, so add the <receiver> tag in manifest file.

Under <application> tag just all the below  <receiver> tag code.

<receiver android:name = "MyReceiver">
            <intent-filter>
                <action android:name = "android.net.conn.CONNECTIVITY_CHANGE"
                    tools:ignore="BatteryLife" />
                <action android:name = "android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
 </receiver>

Step 7 : Call Broadcast receive from MainActivity.java

Then you need to make a call to broadcast receiver so that broadcast receiver get activited from your android app.

This broadcast reciever will keep track of CONNECTIVITY_ACTION like internet connectivity on/off.

MainActivity.java

import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity{

    private BroadcastReceiver MyReceiver = null;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyReceiver = new MyReceiver();
        broadcastIntent();
    }

    public void broadcastIntent() {
        registerReceiver(MyReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(MyReceiver);
    }
}

Finally your android app is ready to check internet connection is on or off.