Home Blog Page 89

Navigation Side Drawer in Flutter with Example

0
Flutter Navigation Drawer With Example
Flutter Navigation Drawer With Example

Hi Guys Welcome to Proto Coders Point, In this Flutter Tutorial we gonna Talk about Flutter Navigation Drawer which is basically a Flutter Slide Menu.

In Flutter Application Development Navigation Drawer are basically used with the Scaffold.drawer Property, where Scaffold must have an appBar to show Drawer opening icon, The Drawer child usually is a ListView which first child is a DrawerHeader that are normally used to show current logIn user data.

The Remaining Drawer children are often been filled using ListTiles.

let’s Start implementing Flutter Navigation drawer Slide menu into our project

Flutter Navigation Drawer with Example

Step 1 : Create a new Flutter Project

offCourse you need to create a new Flutter project or open you existing Flutter project all left to your choice

File > New  > New Flutter Project

Fill all the required details to create  a new project.

Step 2 : Create 3 new Dart files in your flutter project

To create new dart file under your project,

Your_project > lib > (right click) New > Dart File

Then in lib directory you need to create 3 Dart Files and name it as ProfilePage.dart , Setting Page.dart , DrawerCode.dart.

Step 3 : Add a Scaffold Widget with appBar widget and drawer widget in main.dart

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Navigation Drawer"),
      ),
      drawer: DrawerCode(),
    );
  }
}

add a Scaffold widget with a appBar and drawer property in it.

Here DrawerCode is an class that has drawer widget in it.

The complete code of main.dart file is below just copy paste it in main page.

main.dart

import 'package:flutter/material.dart';
import 'DrawerCode.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> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Navigation Drawer"),
      ),
      drawer: DrawerCode(), // this is drawerCode page
    );
  }
}

Step 4 : Adding Required widget in Navigation Drawer Code

Snippet Code

Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          DrawerHeader(
            decoration: BoxDecoration(color: Colors.blue),
            child: Text("Drawer"),
          ),
        ],
      ),

The above Snippet code is for explaination about Flutter Drawer

In Flutter Drawer their must be a child widget i.e ListView.

Then this listView that can have any numbers of children : <Widget>, Here in above snippet code i gave Flutter DrawerHeader widget that will aquire some space in the top of Drawer with some decoration to it, the DrawerHeader in turn has a child which are be any widget here  have just for simple added a Text Widget.

Then the Second widget will be  a ListTiles here is the Snippet code for that.

ListTile(
           leading: Icon(Icons.person_outline),
           title: Text("Profile"),
           onTap: () {
             Navigator.pop(context);
             Navigator.push(
                 context, MaterialPageRoute(builder: (context) => Profile()));
           },
         ),

ListTile widget has a leading property with Icon as an Widget you can set a icon to the flutter Drawer, title property as a Text , and an onTap method property that will handle all the  task when user clicks on the ListTile.

The Complete Code is below just create a DrawerCode.dart file and copy paste the below lines of Flutter Drawer Code.

DrawerCode.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_drawer/ProfilePage.dart';
import 'package:flutter_drawer/SettingPage.dart';

class DrawerCode extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          DrawerHeader(
            decoration: BoxDecoration(color: Colors.blue),
            child: Column(
              children: <Widget>[
                Flexible(
                  child: Container(
                    width: 100,
                    height: 100,
                    margin: EdgeInsets.only(bottom: 5),
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      image: DecorationImage(
                          image: NetworkImage(
                              'https://secure.gravatar.com/avatar/3a719607819fc579c2aafd4d21dad3d1?s=96&d=mm&r=g'),
                          fit: BoxFit.fill),
                    ),
                  ),
                ),
                Text(
                  "Rajat Palankar",
                  style: TextStyle(
                      fontSize: 15.0,
                      fontWeight: FontWeight.w500,
                      color: Colors.white),
                ),
                Text(
                  "https://protocoderspoint.com/",
                  style: TextStyle(
                      fontSize: 12.0,
                      fontWeight: FontWeight.w500,
                      color: Colors.white70),
                ),
              ],
            ),
          ),
          ListTile(
            leading: Icon(Icons.person_outline),
            title: Text("Profile"),
            onTap: () {
              Navigator.pop(context);
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => Profile()));
            },
          ),
          ListTile(
            leading: Icon(Icons.settings_applications),
            title: Text("Setting"),
            onTap: () {
              Navigator.pop(context);
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => Setting()));
              print("Go to Settings");
            },
          ),
          ListTile(
            leading: Icon(Icons.arrow_back),
            title: Text("Logout"),
            onTap: () {
              print("Logout Users");
              Navigator.pop(context);
              SystemNavigator.pop();
            },
          ),
        ],
      ),
    );
  }
}

Step 5 : adding codes for Navigated Drawer pages

Both the below pages will simply show a Text Widget indicating which page is been open.

ProfilePage.dart

When user Tap on menus listTitles from Navigation drawer the user will navigate to the selected option.

import 'package:flutter/material.dart';
import 'package:flutter_drawer/DrawerCode.dart';

class Profile extends StatefulWidget {
  @override
  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Navigator Drawer"),
      ),
      drawer: DrawerCode(),
      body: Center(
        child: Text("Profile Page"),  // this is profile page
      ),
    );
  }
}

SettingPage.dart

import 'package:flutter/material.dart';

import 'DrawerCode.dart';

class Setting extends StatefulWidget {
  @override
  _SettingState createState() => _SettingState();
}

class _SettingState extends State<Setting> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Navigator Drawer"),
      ),
      drawer: DrawerCode(),
      body: Center(
        child: Text("Setting Page"), // Then here is setting page
      ),
    );
  }
}

All set, Now your Flutter Project with Navigation Drawer is ready to test and use.

 

Firebase UI RecyclerView Adapter Android Tutorial with Example

6
Firebase UI RecyclerView Adapte

Hi Guys, Welcome to Proto Coders Point, In this Android tutorial we will implement Firebase UI RecyclerView Adopter

This Project will basically fetch / retrive data from firebase using Firebase UI recyclerview adapter library and display it’s contents in recyclerview as a GridView.

check out :  RecyclerView With GridLayoutManager Show Grid View in androidx this post will help you in understanding basic about RecycleView in android and how to show data in RecyclerView with GridLayoutManager.

Let’s Start Implementation the project.

Demo on How this Project will look at End of this tutorial

Firebase UI RecyclerView Adapter Android Demo

Firebase Ui RecyclerView Adapter Android Tutorial with Example

FirebaseUI makes it simple to bind data from the Firebase Realtime Database to your app’s UI.

Step 1 : Create a new Android Project

OfCouse, your need to create a new android project using android-studio, or else you can make use of your existing android project.

Step 2 : Adding your project to Firebase Console

Check out below video on how to connect android app to firebase console from android studio.

Note: this video is related to Cloud Messaging FCM to send push Notification but the process is same so watch 0 to 2 min minutes of the video to add project to firebase console

or

Follow this steps :

tools -> firebase -> analytics -> log-on Analytics event 

you will see 2 button just click on then

  • Connect your project to firebase.
  • add Analytic dependencies to your project

and you are done your app is now connected to Firebase Console project.

Step 3 : Adding Required Firebase UI Dependencies in your project.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

    implementation 'com.firebaseui:firebase-ui-database:5.0.0' //add firebase ui recyclerview dependency
    implementation 'com.google.firebase:firebase-core:17.2.2' // adding firebase core dependency
    implementation 'com.google.android.material:material:1.2.0-alpha02'  //material design for RecycleView
    implementation 'com.squareup.picasso:picasso:2.71828'  // picasso library dependencies to show image in imageView
}

For this project we need total 4 dependencies

FirebaseUI – this is used to show data retrieved from firebase realtime database in recyclerView.

material – this has the design view for example: this library has recyclerView Widget in it.

picasso library : used to show image fetched from firebase realtime database to imageView.

check out : Picasso android library tutorial – Picasso image loader

Step 4 : Create a RealTime Database in firebase console

Follow this steps to create realtime database.

  1. open your firebase console,
  2. navigate to your project under firebase console
  3. on the left side you will see develop option under that open Database
  4. create a new RealTime Database

Here is how my data looks in Firebase console

Firebase RecycleView Adopter database structure
Firebase database structure

Firebase stored data in JSON format

Here is how the above data looks in json format

{
  "products" : {
    "accessories" : {
      "product1" : {
        "image" : "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRcJUkOrtmOwQFdLVHt--R-q-4SHO5CEFZcmR14LYNhyMLwOUTg",
        "link" : "https://www.amazon.inffff/",
        "name" : "Dumbbell Rack"
      },
      "product2" : {
        "image" : "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT_PQP9-9MWy7lmZBaYMpDb2jyBh4KLyJOA37uSXgiXQZ-3th3e",
        "link" : "https://www.amazon.in/",
        "name" : "Rubic 2*2 Cube"
      },
      "product3" : {
        "image" : "https://support.apple.com/library/content/dam/edam/applecare/images/en_US/homepod/watch-product-lockup-callout.png",
        "link" : "https://www.amazon.in/",
        "name" : "Apple Watch"
      },
      "product4" : {
        "image" : "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQtZ5xPeZyLwIMnIXQgODfr20YSgTUP-6l3Xc-J2pOgUZyPwx3L",
        "link" : "https://www.amazon.in/",
        "name" : "DSLR Camera"
      },
      "product5" : {
        "image" : "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSYYCpkawEmDTQoCipEaP4BGBEHtgAjbJDS6G9CIigDu-EBsG2V",
        "link" : "https://www.amazon.in/",
        "name" : "Bluetooth Headphone"
      },
      "product6" : {
        "image" : "https://images.prismic.io/rpf-products/c4f1986d2ba2737359c10225d1dc1c8d59d3cfd7_compute-module-main-1-1793x1080.jpg?auto=compress,format",
        "link" : "https://www.amazon.in/",
        "name" : "RaspberryPI"
      },
      "product7" : {
        "image" : "https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE4mQFV?ver=c77b&q=90&m=6&h=195&w=348&b=%23FFFFFFFF&l=f&o=t&aim=true",
        "link" : "https://www.amazon.in/",
        "name" : "Play Station"
      }
    }
  }
}

create your own database or just download my database file from https://drive.google.com/file/d/1EPJofN5OA6wQG_jy0tggFZU5PKmz91hC/view?usp=sharing

after downloading just import the file in realtime database

importing JSON file in firebase

Just open realtime database and click on 3 vertical line a popup dropdown list will open click on import JSON > select the file you have downloaded and next..

Hence my Firebase Database structure will get imported into you firebase project.

Then, Now all is been set on the server – side

Just go back to our android Studio.

step 5 : Create a new XML file and Name it as customlayout

customelayout.xml

This xml file 2 views that are ImageView and a text View.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <androidx.cardview.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        app:cardBackgroundColor="#E0D5D5"
        android:orientation="vertical"
        android:layout_margin="5dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            >
            <ImageView
                android:id="@+id/productimage"
                android:layout_width="200dp"
                android:layout_height="200dp"
                android:scaleType="fitXY"
                android:layout_gravity="center_horizontal"
                />
            <TextView
                android:id="@+id/text1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:layout_marginTop="10dp"
                android:background="#004DB4"
                android:textSize="15sp"
                android:textColor="#FFF"
                android:gravity="center"
                android:text="logo1"/>

        </LinearLayout>
    </androidx.cardview.widget.CardView>
</LinearLayout>

Step 6 : Open activity_main.xml and Copy below Code

activity_main.xml

This XML file have only one View that is RecyclerView where we gonna show our data that is retrieve from firebase database using Firebase UI RecyclerViewAdapter.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:theme="@style/Theme.AppCompat.Light">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#056FF0"
        android:textSize="25sp"
        android:layout_gravity="center"
        android:textStyle="bold|italic"
        android:text="Products"/>


    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerViewGirdView"/>


</LinearLayout>

Step 7 : Create a Constructor class that holders all the data from firebase.

you need a class that handles data retrieved from firebase.

create a new java file and name it as product_getter_setter.java this file has a constructor and getter and setter methods that helps in getting and setiing the data.

product_getter_setter.java

package com.ui.recycleview.gridview.firebaserecyclerviewadapter;

public class product_getter_setter {

    String name,image,link;

    public product_getter_setter() {
    }

    public product_getter_setter(String name, String image, String link) {
        this.name = name;
        this.image = image;
        this.link = link;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }
}

Step 8 : Main_Activity.java with has FirebaseRecyclerAdapter method

Main_Activity.java

open Main_Activity.java and copy paste below lines of java code

package com.ui.recycleview.gridview.firebaserecyclerviewadapter;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;

public class MainActivity extends Activity {

    RecyclerView recyclerView;

    Query query1;
    private DatabaseReference mdatabasereference;
    private ProgressDialog progressDialog;
    FirebaseRecyclerAdapter<product_getter_setter, BlogViewHolder> firebaseRecyclerAdapter;
    LinearLayoutManager mLayoutManager;

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

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Loading Products Please Wait...");
        progressDialog.show();

        mdatabasereference = FirebaseDatabase.getInstance().getReference("products").child("accessories");

        recyclerView = (RecyclerView) findViewById(R.id.recyclerViewGirdView);


    }

    @Override
    protected void onStart() {
        super.onStart();
        query1 = FirebaseDatabase.getInstance().getReference().child("products").child("accessories");
        FirebaseRecyclerOptions<product_getter_setter> options =
                new FirebaseRecyclerOptions.Builder<product_getter_setter>()
                        .setQuery(query1, product_getter_setter.class)
                        .build();

        Log.d("Options"," data : "+options);



        firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<product_getter_setter, BlogViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull BlogViewHolder blogViewHolder, final int i, @NonNull product_getter_setter product_get_set_v) {

                blogViewHolder.setname(product_get_set_v.getName());
                String image_url =blogViewHolder.setimage(product_get_set_v.getImage());
                String link= product_get_set_v.getLink();
                Log.d("LINKDATA"," data : "+link);

                blogViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final String productid=getRef(i).getKey();
                        Log.d("productid"," data : "+productid);


                        mdatabasereference.child(productid).addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                String finallink = dataSnapshot.child("link").getValue(String.class);
                                Log.d("productLink"," data : "+finallink);

                                if(finallink!=null)
                                {
                                    Uri uriUrl = Uri.parse(finallink);
                                    Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
                                    startActivity(launchBrowser);
                                }

                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError databaseError) {

                            }
                        });

                    }
                });

            }

            @NonNull
            @Override
            public BlogViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.custom_layout, parent, false);
                progressDialog.dismiss();
                return new BlogViewHolder(view);
            }
        };
        firebaseRecyclerAdapter.startListening();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),2);
        recyclerView.setLayoutManager(gridLayoutManager);

        recyclerView.setAdapter(firebaseRecyclerAdapter);
    }

    public static class BlogViewHolder extends RecyclerView.ViewHolder
    {
        View mView;

        public BlogViewHolder(View itemView)
        {
            super(itemView);
            mView=itemView;



        }
        public void setname(String name)
        {
            TextView ename=(TextView)mView.findViewById(R.id.text1);
            ename.setText(name);

        }

        public String setimage(String url)
        {
            ImageView image = (ImageView)mView.findViewById(R.id.productimage);
            Picasso.get().load(url).into(image);
            return url;
        }
    }
}

Step 9 : Adding Internet Permisson for your project

Then, as you know that we are fetching data from external source i,e our Firebase server, We definitely  need  access to internet permission to be set for our android project

open AndroidManifest.xml file  and app internet permission tag before <application> tag

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

All set now the app is ready to run for testing…..

Download Complete Firebase RecyclerView Adopter project from here:

https://drive.google.com/file/d/1qQRgVGN6nYpFwSh2UrZc74TjRIJOaYv5/view?usp=sharing

RecyclerView With GridLayoutManager Show Grid View in androidx

2

Hi Guys, welcome to Proto Coders Point,In this Android Tutorial we will implement RecyclerView with GridView basically using GridLayoutManager.

The RecyclerView is one of the advance and most flexiable version of ListView and GridView.

It is mostly used to show large number of data sets to the user when user scrolls the view.

it’s is available to use in Material Design of API leven 21 (i.e Android 5.0 Lollipop).

Demo of Final Result of this Tutorial

recycler View with Grid View layout manager

Gradle Dependency to use RecyclerView:

dependencies {
 ...
 implementation "com.android.support:recyclerview-v7:23.23.4.0"
 }

or

if you have latest version of android studio with androidx

you need to add material dependencies

dependencies
{
..............
implementation 'com.google.android.material:material:1.2.0-alpha04' // recycleView is inbuilt in this
}

The material package comes with RecycleView Components.

RecycleView XML code in older version of android studio

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="protocoderspoint.com.recyclerviewexample.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

RecycleView XML code for androidx

<?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">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recycleview"/>
    
</LinearLayout>

RecyclerView With GridLayoutManager in androidx with Example

Let’s us now start implementing our android application with RecycleView with GridLayoutManager with example.

Step 1: Create a New Project And Name It RecyclerViewExample.

OfCouse, your need to create a new android project using android-studio, or else you can make use of your existing android project.

Step 2 : Add Required Dependencies

Once your project is ready you need to first add the recyclerView Dependencies in to your android project so that you can make user of recyclerView widget.

if you are using android-studio version that comes with migrating to androidx then better use material or else you can use recyclerView Dependencies.

The dependencies is been listed above.

Step 3 : Adding recyclerView in activity_main.xml

open > project > app > res > layout > activity_main.xml

And Copy and paste the below lines of xml code with recyclerView widget.

<?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">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recycleview"/>

</LinearLayout>

 

Step 4 : Create a new XML File and name it as row_layout_view.xml

This XML View will be Displayed under RecyclerView in activity_main.xml in a form of GridView

Here we  Simple have an imageView and a textView that will show some date sets.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical"
    android:layout_margin="5dp"
    android:background="@drawable/recyclebackground"
    >
    <!--
    grid items for RecyclerView GridView Example
    -->
    <ImageView
        android:id="@+id/image"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_gravity="center"
        android:scaleType="fitXY"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="....."
        android:gravity="center"
        android:background="#1E88E5"
        android:layout_gravity="center"
        android:textColor="#FAF5F5"
        android:textSize="15sp" />
</LinearLayout>

Step 5 : create a new xml file in drawable

Create a new drawable XML file in Drawable folder and name it recyclebackground.xml 

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <!--
       stroke with color and width for creating outer line
    -->
    <stroke
        android:width="1dp"
        android:color="#000" />
</shape>

 

Step 6: Create a new Adopter Class

Then, you will need a Adopter class that will help you in  handling all the data and display then in recyclerView.

Create a new Adopter Class and name it as CustomRecycleAdopter.java

App > java > your Package (Right click) > New > java class

This CustomRecycleAdopter class will extends RecyclerView.Adapter class which incluse Viewholder in it.

Then  we will implement some override methods and create a constructor to get the data from Main_Activity Class.

In CustomRecycleAdapter class we have 2 methods those are OnCreateViewHolder that helps use to inflate the row_layout_view.xml view Items and then pass it to ViewHolder and the other method is onBindViewHolder that is been used to set the data in the views by the help of ViewHolder.

Then Finally we implement the setOnClickListener on the itemview that show use which gridView in recyclerView was clicked by the user

Then you Just Copy paste the Below Code

package com.ui.recycleview.gridview.layoutmanager;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
public class CustomRecyclerViewAdopter extends RecyclerView.Adapter {
    ArrayList personNames;
    ArrayList personImages;
    Context context;
    public CustomRecyclerViewAdopter(Context context, ArrayList personNames, ArrayList personImages) {
        this.context = context;
        this.personNames = personNames;
        this.personImages = personImages;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // infalte the item Layout
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout_view, parent, false);
        // set the view's size, margins, paddings and layout parameters
        MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        // set the data in items
        MyViewHolder viewHolder= (MyViewHolder)holder;
        ((MyViewHolder) holder).name.setText( personNames.get(position).toString());
        ((MyViewHolder) holder).image.setImageResource((Integer) personImages.get(position));
        // implement setOnClickListener event on item view.
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context,"Person : "+(position+1),Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    public int getItemCount() {
        return personNames.size();
    }
    public class MyViewHolder extends RecyclerView.ViewHolder {
        // init the item view's
        TextView name;
        ImageView image;
        public MyViewHolder(View itemView) {
            super(itemView);
            // get the reference of item view's
            name = (TextView) itemView.findViewById(R.id.name);
            image = (ImageView) itemView.findViewById(R.id.image);
        }
    }
}

Step 7 : Passing Data from Main_Activity.java to CustomRecyclerAdopter.java

Now, Firstly you need to get References to recycleView and then pass data to Adopter.

Then we are creating a list of data using java ArrayList name it as Person Name and likewise i have created a list of Images using ArrayList.

There after we set the recyclerView with GridLayoutManager and then we set the Adopter that show the Grid Items in out RecyclerView Widget.

Main_Activity.java

package com.ui.recycleview.gridview.layoutmanager;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
    // ArrayList for person names
    ArrayList personNames = new ArrayList<>(Arrays.asList("Person 1", "Person 2", "Person 3", "Person 4", "Person 5", "Person 6", "Person 7","Person 8", "Person 9", "Person 10", "Person 11", "Person 12", "Person 13", "Person 14"));
    ArrayList personImages = new ArrayList<>(Arrays.asList(R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp,R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp));
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        // get the reference of RecyclerView
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycleview);

        // set a GridLayoutManager with default vertical orientation and 2 number of columns
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),2); // you can change grid columns to 3 or more

        recyclerView.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
        //  call the constructor of CustomAdapter to send the reference and data to Adapter
        CustomRecyclerViewAdopter customAdapter = new CustomRecyclerViewAdopter(MainActivity.this, personNames,personImages);
        recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
    }
}

 

And the last thing is that you need to add some images in drawable to show them into Recycle GridView

I have simple created a vector images assets under drawable folder.

Just Right Click on Drawable  folder > New > Vector Assets

person_blue.xml

<vector android:height="24dp" android:tint="#0324FA"
    android:viewportHeight="24.0" android:viewportWidth="24.0"
    android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="#FF000000" android:pathData="M12,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zM12,14c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z"/>
</vector>

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.