Home Blog Page 90

Flutter Toast Message Example – Show Toast in flutter

3
Flutter Toast Message
Flutter Toast Message

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will see how can we show toast message in Flutter app.

visit official Site to learn more https://pub.dev/packages/fluttertoast

What is Toast Message?

Some Times Toast Messages are also called as Toast Notification.

It’s a small message that pops up at the bottom of the device screen and immediately disappears on its own after a delay of few seconds,

This are mostly used to show a feedback on the operation that is preformed by the user.

So, Let’s Begin Implementing FlutterToast Message into your project

Result of the Tutorial

flutter toast message top
flutter toast message top

Step 1 : Adding Flutter Toast Dependencies in project

To get access to Futter Toast you need to add it’s Plugin into your Flutter Project

Open pubspec.yaml  and add the dependencies plugin

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.2
  fluttertoast: ^3.1.3    // add this line

Note :  This Plugin version might get updated so better be updated with latest version ( here )

Step 2 : Import the Fluttertoast dart package

Now, once you have added dependencies into you project now you can user the Flutter Toast plugin anywhere in your project to show the toast message

Open main.dart  and then at the top import the package

import 'package:fluttertoast/fluttertoast.dart';

Step 3 : How to use the Toast message widget in flutter

Fluttertoast.showToast(
        msg: "This is Bottom Short Toast",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0
    );

There are several properties that you can user to show the Toast message.

propertyDescription
msgString ( Required )
toastlengthToast.LENGTH_SHORT or Toast.LENGTH_LONG
gravityToastGravity.TOP or ToastGravity.CENTER or ToastGravity.BOTTOM
timeInSecforIosonly for Ios ( 1 sec or more )
backgroundColorColors.blue
textColorColors.red
fontSize16.0

And to Cancel all the Toast Calls then you can user

FlutterToast.cancel() : This will Immediately cancel all the request to show Message to user.

If you don’t want to user androidx then make user of older version of fluttertoast 2.211

How to Show Toast in Flutter App with Example  – Complete Code

Copy and paste the below lines of code in main.dart  file to make toast message work

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.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: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  Function toast(
      String msg, Toast toast, ToastGravity toastGravity, Color colors) {
    Fluttertoast.showToast(
        msg: msg,
        toastLength: toast,
        gravity: toastGravity,
        timeInSecForIos: 1,
        backgroundColor: colors,
        textColor: Colors.white,
        fontSize: 16.0);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Toast"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("Demo on Flutter Toast Message Plugin"),
            SizedBox(
              height: 20.0,
            ),
            MaterialButton(
              elevation: 5.0,
              height: 50.0,
              minWidth: 100,
              color: Colors.blueAccent,
              textColor: Colors.white,
              child: Text("Show Toast at Bottom"),
              onPressed: () {
                toast(
                    "This is Demo 1 Toast at BOTTOM",
                    Toast.LENGTH_LONG,
                    ToastGravity.BOTTOM,
                    Colors.green); // calling a function to show Toast message
              },
            ),
            SizedBox(
              height: 20.0,
            ),
            MaterialButton(
              elevation: 5.0,
              height: 50.0,
              minWidth: 100,
              color: Colors.redAccent,
              textColor: Colors.white,
              child: Text("Show Toast at TOP"),
              onPressed: () {
                toast(
                    "This is Demo 2 Toast at top",
                    Toast.LENGTH_SHORT,
                    ToastGravity.TOP,
                    Colors.red); // calling a function to show Toast message
              },
            ),
          ],
        ),
      ),
    );
  }
}

And there you go App is ready to show the toast message in flutter to the users.

Recommended Articles

Custom toast in android

Bot toast flutter

Toast Message using VelocityX

Connect flutter app to firebase Console – firebase integration – Android

2
firebase integration in flutter Application
firebase integration in flutter Application

Hi Guys, Welcome to Proto Coders Point , In this Tutorial we are going to add Firebase Integration in Flutter Project.

To make user of Firebase Services in our Flutter Application, We must add Firebase SDK and Required Dependencies in our Flutter Project.

Let’s Integrate Firebase with Flutter Application by Following below steps.

VIDEO TUTORIAL

 

Step1 : Create a new Flutter Project in android Studio

As usually you need to Create a new Flutter Project in your android-studio.

File > New > New Flutter Project

Step 2 : Create a new Firebase Project in firebase Console.

create add new project in firebase console
create add new project in firebase console

Go to Firebase console Sign-In with your Google Account, you will see and cardView to add new Firebase Project, Just Click on it

1. Give a name to your project in Firebase Console.

Giving name you firebase project in console
Giving name you firebase project in console

   2. Configure Google Analytic Give some name, Agree the Form and Continue.

Configure google analytic
Configure google analytic

Just Configure the Google Analytic and accept all the Agreement Form and Continue to next process.

creating Firebase project completed
creating Firebase project completed

Then,  Firebase Proejct for your flutter app is successfully been created now hit the continue button.

Step 3 : Get Started by adding Firebase to your app

Their are 4 platform where you are integrate your Flutter project with Firebase as backend.

iOS, Android, Web and Unity development. In this Tutorial we are integrating Firebase with Flutter Application Development ( Android )

So Just Click on Android Icon  if you want to integrate Firebase into your flutter android part.

get Started adding android firebase
get Started adding android firebase

Step 4: Add Firebase to your Android Project.

1. Android Package Name

Navigate / Open build.gradle > search for applicationId ” ………………..”  and Click next.

How to Find Application Id in flutter project
How to Find Application Id in flutter project

On the right side you will see your flutter project under the project extend android > app >build.gradle  scroll-down and search for applicationId and Copy the Id also knows as packageName

Then you have copyed your AppID, come back to firebase console and paste the AppID and hit Next button thus firebase can generate a json file for your application google_services.json.

adding register app and download google-servicesjson file
adding register app and download google-servicesjson file

 2. Adding Google_services.json file

Download Config File Genarated by Firebase copy the file and add it to your project under

Your Project Name > Android > app folder

google services file added
google services file added

Step 5 : Add Firebase SDK to your Project

 1. Project-Level build gradle

Add Google Service Dependencies

Open Project Level Build gradle your project > android > build.gradle  and add the classpath of google services in dependencies.

dependencies {
    ....................................
    classpath 'com.google.gms:google-services:4.3.2'

}

2. App-Level Build Gradle

Add Firebase Analytics dependencies.

Open App Level Build gradle your project > android > app > build.gradle  and add the implemention of google analytics in dependencies.

dependencies {
    ......
    ......
     .....
    implementation 'com.google.firebase:firebase-analytics:17.2.0'  // add this line
}

apply plugin: 'com.google.gms.google-services' // add this line at the botton

Here you go Firebase is added successfully been added in you android section of your flutter project.

Now Once we have added our Flutter project in firebase console, Now it’s time to incorporate the flutter Package that will allow us to work with firebase using dart programming

As you know there are whole bunch of firebase services out their.

Firebase Flutter Fire plugin
Firebase Flutter Fire plugin

Here firebase_core must be added into your project of you want to use any services of firebase.

Firebase Core its the core to start implementing firebase in our flutter project.

Just for the simple i make adding 3 FlutterFire plugin into my project.

Adding Flutter Fire plugin  depencencies  in pubspec.yaml  and then click on Packages get to get all the packaged flutter firebase classes.

adding dependencies in pubspec.yaml
adding dependencies in pubspec.yaml

To use any of this firebase services you just need to import the packages where you want to use then

For example :

import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

 

That’s All your Project is now been added to Firebase console and ready to use firebase services.

 

Android AsyncTask Tutorial Handling JSON and parse JSON

1
Android AsyncTask Tutorial Handling JSON and parse JSON
Android AsyncTask Tutorial Handling JSON and parse JSON

Hi Guys, Welcome to Proto Coders Point  In this Android Tutorial we will Learn about Android  AsyncTask  and Learn How to Fetch JSON data using AsyncTask and Handle them.

Final Project Result

Android AsyncTask Tutorial Handling JSON

What is AsyncTask ?

In android, AsyncTask is been used to run any process that should be run in background and likewise update the UI(User Interface).

Mainly AsyncTask is used to fetch data from a server and this will not effect our main Thread that is handling UI.

AsyncTask ( Asynchronous Task) Help you n running the background Process which will create a seperate Thread to run in background and then Synchronize again with the main Thread, This process will not disturb the main Thread and UI process will run smoothly.

This class will override at least one method i.e doInBackground(Params) and most often will override second method onPostExecute(Result).

To Execute AsyncTask you need to called Execute() method.

The Flow of AsyncTask Process

Androi AsyncTask Flow Process
Androi AsyncTask Flow Process

When AsyncTask class is executed  onPreExecute() is called then doInBackground() is called to execute background processed and at last onPostExecute() method is called to update the data to UI.

Syntax of AsyncTask:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {

@Override
protected void onPreExecute() {
    super.onPreExecute();
    // mostly used to show progress dialog
    // display a progress dialog for good user experiance
   
}
@Override
protected Long doInBackground(URL... urls) {
// code that will run in the background
return ;
}

@Override
protected void onProgressUpdate(Integer... progress) {
// receive progress updates from doInBackground
}

@Oveerride
protected void onPostExecute(Long result) {
// update the UI after background processes completes
}
}

Here is How to execute AsyncTask class from main Thread

new DownloadFilesTask().execute();

Android AsyncTask Example Handling JSON and parse JSON

In the Below Example of AsyncTask We are performing a network operation, where we gonna fetch data from JSON File and Display them in our UI.

My JSON DATA URL : https://protocoderspoint.com/jsondata/superheros.json

Step 1 : As usual Create a new Android project in android studio.

File > New > New Project

Give relevent name to your project

Step 2 : Adding picasso library into our project Dependencies

Gradle Script > build.gradle(app level)

dependencies {
........
.......
implementation 'com.squareup.picasso:picasso:2.71828'
}

Step 3 : UI Design  Open res -> layout ->activity_main.xml add following code

Here we have 5 Views,

  • Button that Perform Click event.
  • Spinner used to select lists.
  • 2 TextViews to Display data fetched from server.
  • 1 ImageView to Display Image from server.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/displayData"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:background="@color/colorPrimary"
        android:text="Display Hero Data"
        android:textColor="#fff"
        android:textSize="20sp" />

    <Spinner
        android:id="@+id/selectHero"
        android:layout_marginTop="20dp"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

    <TextView
        android:id="@+id/titleTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Hero Name: "
        android:visibility="gone"
        android:textColor="#000"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/categoryTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="His Ability: "
        android:visibility="gone"
        android:textColor="#000"
        android:textSize="18sp" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:visibility="gone"
        android:fitsSystemWindows="true"
        android:layout_marginTop="20dp"
        android:scaleType="centerCrop" />

</LinearLayout>

Step 4: Java Code Open src -> package -> MainActivity.java

In MainActivity.java code.

We first refer the views present in XML File like Buttons, TextView, Spinner and ImageView.

Their after we perform onClick event that execute AsyncTask Class “MyAsyncTasks”.

Then  In doInBackground() we fetch all the data from the server link mentioned above.

Then, In onPostExecute method we simply parse the JSON data fetched and Display then in the UI.

and We have used Picasso Library just to show the Fetch URL image in the ImageView.

package com.ui.asynctaskexample;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    String apiUrl = "https://protocoderspoint.com/jsondata/superheros.json";
    String title, image, category;
    TextView titleTextView, categoryTextView;
    ProgressDialog progressDialog;
    Button displayData;
    ImageView imageView;

    int index_no;
    Spinner spinner;


    String[] HerosNameList = { "Flash", "SuperMan", "Thor", "Hulk", "Venom"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // get the reference of View's
        titleTextView = (TextView) findViewById(R.id.titleTextView);
        categoryTextView = (TextView) findViewById(R.id.categoryTextView);
        displayData = (Button) findViewById(R.id.displayData);
        imageView = (ImageView) findViewById(R.id.imageView);


        spinner=(Spinner)findViewById(R.id.selectHero);

        //Creating the ArrayAdapter instance having the country list
        ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,HerosNameList);

        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //Setting the ArrayAdapter data on the Spinner
        spinner.setAdapter(aa);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
               index_no=position;

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        // implement setOnClickListener event on displayData button
        displayData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // create object of MyAsyncTasks class and execute it
                MyAsyncTasks myAsyncTasks = new MyAsyncTasks();
                myAsyncTasks.execute();
            }
        });
    }

    public class MyAsyncTasks extends AsyncTask<String, String, String> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // display a progress dialog for good user experiance
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("Please Wait");
            progressDialog.setCancelable(false);
            progressDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            // implement API in background and store the response in current variable
            String current = "";
            try {
                URL url;
                HttpURLConnection urlConnection = null;
                try {
                    url = new URL(apiUrl);

                    urlConnection = (HttpURLConnection) url.openConnection();

                    InputStream in = urlConnection.getInputStream();

                    InputStreamReader isw = new InputStreamReader(in);

                    int data = isw.read();


                    while (data != -1) {
                        current += (char) data;
                        data = isw.read();
                        System.out.print(current);

                    }

                   Log.d("datalength",""+current.length());
                    // return the data to onPostExecute method
                    return current;

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (urlConnection != null) {
                        urlConnection.disconnect();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                return "Exception: " + e.getMessage();
            }
            return current;
        }

        @Override
        protected void onPostExecute(String s) {

            Log.d("data", s.toString());
            // dismiss the progress dialog after receiving data from API
            progressDialog.dismiss();
            try {

                JSONObject jsonObject = new JSONObject(s);

                JSONArray jsonArray1 = jsonObject.getJSONArray("superheros");

                JSONObject jsonObject1 =jsonArray1.getJSONObject(index_no);
                title = jsonObject1.getString("name");
                category = jsonObject1.getString("power");
                image=jsonObject1.getString("url");

                //make all the view Visible when data is ready to show
                titleTextView.setVisibility(View.VISIBLE);
                categoryTextView.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.VISIBLE);

                titleTextView.setText("Hero Name : "+title);
                categoryTextView.setText("His Ability : "+category);
                Picasso.get().load(image).into(imageView);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }
}

Step 5 : Adding a INTERNET PERMISSION in manifest.xml file

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

And their you go the app is ready to get Tested.

 

More on:  How to Parse JSON data in flutter app development

Flutter Profile Page UI :  Flutter Profile Page UI Design

 

 

 

Flutter Sliver App Bar – An Collapsing ScrollView App Bar

0
Flutter Sliver App Bar Example
Flutter Sliver App Bar Example

Hi Guys, Welcome to Proto Coders Point , In This Tutorial we gonna implement A Sliver App Bar in Flutter App.

What is Sliver AppBar Class?

A Sliver AppBar in Flutter is similar to any normal AppBar, The Different here is only that Sliver AppBar come with ScrollView effect.

The Sliver App bar should be the first child of a CustomScrollView, Using with we can integrate the appbar with a scroll view so that it can vary in height and other content of the scrollview.

Implementation with Sliver AppBar Widget

Below Examples will show you how appbars can we integrated with different configurations and act with different behaviour when any user Scrolls the View up or down.

Example 1:

When App bar with

  1. floating: false,
  2. pinned: false,
  3. snap: false

Sliver App bar flutter
Example 1

StateFull Class Code

class _NewPageState extends State<NewPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            expandedHeight: 150.0,
            floating: false,
            pinned: false,
            snap: false,
            actions: <Widget>[
              IconButton(
                icon: const Icon(Icons.add_circle),
                onPressed: () {},
              ),
            ],
            flexibleSpace: FlexibleSpaceBar(
              title: Text(
                "Sliver App Bar Example",
                style: TextStyle(fontSize: 15),
              ),
              background: Image.asset(
                'images/images.jpeg',
                fit: BoxFit.cover,
              ),
            ),
          ),
          SliverFillRemaining(
            child: new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset('images/protocoderspointlogo.png'),
                  SizedBox(
                    height: 20.0,
                  ),
                  Text(
                    "This is an Simple Sliver App Bar Flutter Example",
                    style:
                        TextStyle(fontSize: 15.0, fontWeight: FontWeight.w800),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

 

Example 2 :

When Sliver App bar with

  1. floating: true,
  2. pinned: true,
  3. snap: false

sliver app bar example 2 scrollview

 

The Code base for this to work is very simply in the above lined of code you just need to change floating to true and pinned to true,  this Configuration will simple pin the app bar at the top of the screen when used scroll through the app and  other remaining widget will simple scroll to the end.

StateFull Class Code

class _NewPageState extends State<NewPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            expandedHeight: 150.0,
            floating: true, //change is here 
            pinned: true, //change si
            snap: true,
            actions: <Widget>[
              IconButton(
                icon: const Icon(Icons.add_circle),
                onPressed: () {},
              ),
            ],
            flexibleSpace: FlexibleSpaceBar(
              title: Text(
                "Sliver App Bar Example",
                style: TextStyle(fontSize: 15),
              ),
              background: Image.asset(
                'images/images.jpeg',
                fit: BoxFit.cover,
              ),
            ),
          ),
          SliverFillRemaining(
            child: new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset('images/protocoderspointlogo.png'),
                  SizedBox(
                    height: 20.0,
                  ),
                  Text(
                    "This is an Simple Sliver App Bar Flutter Example",
                    style:
                        TextStyle(fontSize: 15.0, fontWeight: FontWeight.w800),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

Explaination of above code

1. As i said before that Sliver App bar must be the child of CustomScrollView to get Scrolling effect, The CustomScrollView will make  the SliverAppBar into Scrolling.

2. Here i have Used an IconButton just to Show that you can even add IconButton Widget into the Appbar. i’e IconButton, which is used with actions to show buttons on the app bar.

Snippet

actions: <Widget>[
              IconButton(
                icon: const Icon(Icons.add_circle),
                onPressed: () {},
              ),
            ],

Flexible SpaceBar  is used so that we can easily set and maximum expandable size to it when user scroll the app Down-words,

And Even we can set many other properties like background,title etc

SliverFillRemaining that fills the remaining space in the viewport. In Other words The Remaining  body should not be null, is the Remaininig body is null then the app bar scrollview will not work as accepted, this value cannot be null.

So i have just Defined some widget in the remaining part in Sliver Fill Remaining

which has a child which is set to center , in turn has a child Column, then This Column have 3 children widget Image,SixedBox,and a Text.

Snippet Code

SliverFillRemaining(
            child: new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset('images/protocoderspointlogo.png'),
                  SizedBox(
                    height: 20.0,
                  ),
                  Text(
                    "This is an Simple Sliver App Bar Flutter Example",
                    style:
                        TextStyle(fontSize: 15.0, fontWeight: FontWeight.w800),
                  ),
                ],
              ),
            ),
          )

 

Complete Source code of Flutter Sliver App Bar – An Collapsing ScrollView App Bar 

main.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(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: NewPage(),
    );
  }
}

class NewPage extends StatefulWidget {
  @override
  _NewPageState createState() => _NewPageState();
}

class _NewPageState extends State<NewPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            expandedHeight: 150.0,
            floating: true,
            pinned: true,
            snap: true,
            actions: <Widget>[
              IconButton(
                icon: const Icon(Icons.add_circle),
                onPressed: () {},
              ),
            ],
            flexibleSpace: FlexibleSpaceBar(
              title: Text(
                "Sliver App Bar Example",
                style: TextStyle(fontSize: 15),
              ),
              background: Image.asset(
                'images/images.jpeg',
                fit: BoxFit.cover,
              ),
            ),
          ),
          SliverFillRemaining(
            child: new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset('images/protocoderspointlogo.png'),
                  SizedBox(
                    height: 20.0,
                  ),
                  Text(
                    "This is an Simple Sliver App Bar Flutter Example",
                    style:
                        TextStyle(fontSize: 15.0, fontWeight: FontWeight.w800),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

 

Flutter Circular Progress Indicator – Modal Progress HUD Flutter Library

5
Flutter Circular Progress Indicator

Hi  Guys, Welcome to Proto Coders Point , In this Tutorial is all about a flutter Widget Library known as Modal Progress HUD, By the use of this library we can show a Circular Progress Indicator in our flutter Applications.

Demo on Progress Indicator

Flutter Circular Progress Indicator

Modal Progress hud

In flutter progress indicator is an simple widget that is been wrap into other flutter widgets to enable modal progress indicator.

Here HUD stands for Heads Up Display.

let’s go straight into implementation of Flutter Circular Progress Indicator

Installation of Modal Progress HUD in our Flutter Project

To user this Package as a library

You need to add the required package’s dependencies into pubspec.yaml file

progress modal hud dependencies
progress modal hud dependencies

dependencies: 
  modal_progress_hud: ^0.1.3

Then, just click on Package Get

The above library of flutter circular progress indicator dependencies library version may update so to get latest version visit official site here.

Now you can use them by importing wherever required.

Importing the flutter progress indicator package wherever required

Now in your Dart code (main.dart), you can use:

import 'package:modal_progress_hud/modal_progress_hud.dart';

After importing the library in the required flutter page (main.dart)

Now, all you have to do is simply wrap your widget as a child of ModalProgressHUD, typically a form, together with a boolean that is maintained in local state.

Snippet Example Code

class _MyHomePage2State extends State<MyHomePage2> {
   bool show=false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Progress Indicator Example"),
      ),
      body: ModalProgressHUD(
        inAsyncCall: show, // here show is bool value, which is used to when to show the progess indicator
        child: Column(
          children: <Widget>[
            Text(" Modal Progress Indicator ")
          ],
        ),
      ),
    );
  }
}

inAsyncCall : Accepts boolean type value, by setting this to true we can show the progress indicator in our flutter application.

The current parameters are customizable in the constructor

ModalProgressHUD(
  @required inAsyncCall: bool,
  @required child: Widget,
  opacity: double,
  color: Color,
  progressIndicator: CircularProgressIndicator,
  offset: double
  dismissible: bool,
);

Flutter Circular Progress Indicator  example with Source Code

main.dart

Copy Paste the below code in main.dart file to make it work.

import 'package:flutter/material.dart';
import 'package:modal_progress_hud/modal_progress_hud.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: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  bool showProgressloading = false; // set to false
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Modal Progress HUD Example"),
      ),
      body: ModalProgressHUD(
        inAsyncCall: showProgressloading, // is set to false, so then login button is pressed it gets activated.
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 24.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Center(
                child: Text(
                  "Log-In",
                  style: TextStyle(
                      fontSize: 25,
                      fontStyle: FontStyle.italic,
                      fontWeight: FontWeight.w800),
                ),
              ),
              SizedBox(
                height: 48.0,
              ),
              TextField(
                keyboardType: TextInputType.emailAddress,
                showCursor: true,
                decoration: InputDecoration(hintText: "Enter your Email"),
                onChanged: (value) {},
              ),
              SizedBox(
                height: 15.0,
              ),
              TextField(
                obscureText: true,
                showCursor: true,
                decoration: InputDecoration(hintText: "Enter your password"),
                onChanged: (value) {},
              ),
              SizedBox(
                height: 15.0,
              ),
              MaterialButton(
                elevation: 5.0,
                color: Colors.blueAccent,
                child: Text(
                  "Log-In",
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () {
                  print("Button Clicked");

                  setState(() {
                    showProgressloading = true; // then login button is pressed the circular flutter indicator will get active
                  });
                  // stop the Progress indicator after 5 seconds
                  new Future.delayed(const Duration(seconds: 5), () {
                    setState(() => showProgressloading = false);
                  });
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

So the Source code will show a simple Login screen.

It have 2 TextField and a Button.

When the user press the login button the Flutter Circular progress indicator will be show.

  1. On initial load, showProgressloading is false which causes your child widget to display
  2. When Login button is pressed, showProgressloading is set to true, and will display the modal progress.
  3. Then once Futur Delayed is Completed,showProgressloading is set back to false, This will hide the progress Indicator.

and here i m making user of Future.delayed to show the progress indicator for 5 seconds.

you can just copy paste the above lines of code into your project.