Home Blog Page 68

Flutter Firebase Google Sign In method – Getx firebase Authentication

1
Google Sign in using Flutter Getx

Hi Guys, Welcome to Proto Coders Point,

This Flutter Tutorial is the 3 part of Getx Firebase Authentication, so in this Flutter Dev Tutorial we will add one more feature i.e. Google Sign In using which your application user can easily make use of google authentication to sign in/ get authorized to your app.

Video Tutorial on Firebase Flutter Google Sign In using GetX

Flutter Firebase Google Sign In method – Getx firebase Authentication

Method in GetXController Class

Firebase GoogleSignIn.SignIn() method

 GoogleSignIn googleSignIn = GoogleSignIn(scopes: ['email']);  //initialization with scope as Email

void google_signIn() async{

    final GoogleSignInAccount googleUser = await googleSignIn.signIn();  //calling signIn method // this will open a dialog pop where user can select his email id to signin to the app

    final GoogleSignInAuthentication googleAuth = await googleUser.authentication;  

    final AuthCredential credential = GoogleAuthProvider.getCredential(
      idToken: googleAuth.idToken,                                           //create a login credential
      accessToken: googleAuth.accessToken
    );

    final User user = (await _auth.signInWithCredential(credential).then((value) => Get.offAll(Dashboard())));  //if credential success, then using _auth signed in user data will be stored 

 }

GoogleSignIn.SignOut() method

Using which user can easily signout from your flutter application.

void google_signOut() async{
   await googleSignIn.signOut().then((value) => Get.offAll(LoginPage()));
}

This will signOut the user and navigate the use back to LoginPage().



You just need to call the above GetX method to GoogleSignIn when a Raised button is been pressed

you can easily do it by making use of GetX Controller.

Example:

GestureDetector(
         onTap: (){
           print("Google Clicked");
           controller.google_signIn();   // calling getx controller method, when a image icon is been taped
         },
         child: Container(
           width: 30,
           height: 30,
           child: SvgPicture.asset("images/assets/google.svg"),
         ),
       ),

Then this icon will be taped, a google_signIn method will get called. then the user will be shown a dialog with google gmail signIn.

Example:

google gmail sign in flutter
google gmail sign in flutter

Then, to Sign out, from dashboard user can do it simply by pressing on a signOut button

 RaisedButton(onPressed: (){
              //logout
              controller.google_signOut();
            },
   child: Text("Sign out Google Sign in"),
),

This button, when pressed will call getx controller signout method

Check out previous part 1 & part 2 of Flutter Firebase Authentication using Getx library

Part 1: Firebase Registration & Login :

Website: https://protocoderspoint.com/flutter-firebase-authentication-using-getx-library-velocity-x/

Video Tutorial on Getx: 

Part 2 : Forgot password & delete firebase auth account

Website: https://protocoderspoint.com/flutter-firebase-authentication-using-getx-library-forgot-password-delete-account/

Video Tutorial on Getx: 

Velocity X Toast message using VxToast and Show Loading Progress

0

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will show Toast message in flutter & show loading progress using  VELOCITY X” Library developed using Flutter SDK by Pawan Kumar.

Installation of Velocity X in your Flutter project

Step 1: Create a new Flutter

Offcouse you need to create a new Flutter Project in your favorite IDE, In my Case i m making us of Android-Studio to build Flutter Android & IOS apps.

Step 2: Open Pubspec.yaml file & add Velocity X dependencies

Once your Project is been build successful, Navigate/Open pubspec.yaml, and under dependencies section add velocity x library dependencies.

You can install the above dependency by running the following code with pub: flutter pub get

Step 3: Import Velocity X

Once Velocity X is been added you need to import velocity x where required.

import "package:velocity_x/velocity_x.dart";


VxToast

Using Velocity X you can easily show toast message and you can even show custom toast message.

Velocity X comes with a class VxToast to show a toast in your flutter apps.

Using VxToast class

VxToast.show(context, msg: "Hello from vx"); //using VxToast class

Using context

context.showToast(msg: "Hello from vx");

Show Loading or Circular progress indicator using VxToast

Show Circular Loading using VxToast.showloading class

VxToast.showLoading(context, msg: "Loading");

Loading Indicator using Context

final close = context.showLoading(msg: "Loading");
Future.delayed(2.seconds, close); // Removes toast after 2 seconds

In  above snippet code you just need to create a final variable with velocity X show loading with some message as parameter and  to remove the toast from flutter app screen make us of future delayed to remove the toast loading indicator.

Properties of VxToast

Properties Default Description
showTime 2000 To set duration of the toast
bgColor __ Sets background color of the toast
textColor __ Sets text color of the toast
textSize 14 Sets text font size of the toast
position VxToastPosition.bottom Available options – top, center, bottom
pdHorizontal 20 Sets horizontal padding
pdVertical 10 Sets vertical padding

Make use of above Velocity X VxToast Properties to customize your toast message or loading indicator.

Velocity X Toast – Example

VxToast.show(context, msg: "Showing Toast",bgColor: Colors.blue,textColor: Colors.black);

output:
velocity x toast

VxToastPosition

VxToast.show(context, msg: "Showing Toast",bgColor: Colors.blue,textColor: Colors.black,position: VxToastPosition.top);

velocity x vxtoastposition

 

Flutter Firebase Authentication using GetX library – Forgot password & Delete Account

0
flutter firebase authnetication using getx - forget password & delete account

Hi Guys, Welcome to Proto Coders Point.

In this Flutter Tutorial we will continue the Integration of Firebase Authentication using GetX flutter library.

Video Tutorial 

Check Out Part 1 of this Firebase Authentication using GetX Library.

https://protocoderspoint.com/flutter-firebase-authentication-using-getx-library-velocity-x/

In the continuation of previous tutorial, We are going to add feature like Flutter Firebase Forget password(using this user can send password reset email flutter) and Firebase Delete auth Account (using which user can permanently delete firebase auth account from firebase auth authentication)

So let’s begin

Flutter Firebase Authentication using GetX library – Forgot password & Delete Account (Part 2)

Forget password / Firebase send password reset email

So if a user forgot his authentication and then he want to reset his firebase password then a developer can make use of a firebase function

sendPasswordResetEmail

that will help developer to send password reset email to user email address,

To build this we need a UI from where a user can request for a password reset,
Note: For this user should atleast remember his email account using which he had create user account on firebase console authentication.

Understanding the process of Authentication password Change/forgot password change

1st Step: User will click Forgot Password button or text

2nd Step: User will be in reset password UI page where he enter his email and the submit

forgot password screen UI flutter

3rd Step : User will get email on his email with a link to reset firebase email auth password

firebase password reset email

4th Step : Clicking on that link user will change the password



Snippet Code / Method to send password reset email 

Called this method will send a request to firebase auth to send a email link to reset the password

void sendpasswordresetemail(String email) async{
    await _auth.sendPasswordResetEmail(email: email).then((value) {
      Get.offAll(LoginPage());
      Get.snackbar("Password Reset email link is been sent", "Success");
    }).catchError((onError)=> Get.snackbar("Error In Email Reset", onError.message) );
 }

So from UI or reset password UI page you need to called this method and  pass a parameter email i.e. entered by the user. (Complete code is below)


Deleting account / Firebase auth delete created account

Note: To delete a account, the user must enter his email and password to re-check his authentication, In other words we need to check if the account holder is the one who want to delete his account.

Understanding the process of firebase Authentication delete account

1st Step: Create a user for deleting account UI
              Using which user can delete his account 

delete firebase auth account

2nd Step: Pass parameter email and password to method

Code is below

3rd Step: Check for Firebase AuthCredential using EmailAuthProvider.credential

4th Step: Then make use of user and reauthentictewithcredential to check if credential get successed or failed.

5th Step : Depending on the credential result if credential pass then just delete the user account and move the user to LoginPage()  

Below Snippet Code

void deleteuseraccount(String email,String pass) async{
    User user = await _auth.currentUser;

    AuthCredential credential = EmailAuthProvider.credential(email: email, password: pass);

    await user.reauthenticateWithCredential(credential).then((value) {
      value.user.delete().then((res) {
        Get.offAll(LoginPage());
        Get.snackbar("User Account Deleted ", "Success");
      });
    }

    ).catchError((onError)=> Get.snackbar("Credential Error", "Failed"));
  }


So from UI or delete firebase auth account UI page you need to called this method and  pass a parameter email and password i.e. entered by the user. (Complete code is below)

Complete source code – Firebase Forget password & delete auth account

https://github.com/RajatPalankar8/Flutter_Login_Registration_UI

FirebaseController.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_login_ui/Screen/Dashboard.dart';
import 'package:flutter_login_ui/Screen/LoginPage.dart';
import 'package:get/get.dart';
import 'package:cloud_firestore/cloud_firestore.dart';


class FirebaseController extends GetxController{

  FirebaseAuth _auth = FirebaseAuth.instance;

  Rx<User> _firebaseUser = Rx<User>();

  String get user => _firebaseUser.value?.email;

  @override
  void onInit() {
    _firebaseUser.bindStream(_auth.authStateChanges());
  }


  // function to createuser, login and sign out user

 void createUser(String firstname,String lastname,String email,String password) async
 {
   CollectionReference reference = FirebaseFirestore.instance.collection("Users");

   Map<String,String> userdata ={
     "First Name": firstname,
      "Last Name": lastname,
      "Email":email
   };

   await _auth.createUserWithEmailAndPassword(email: email, password: password).
   then((value) {

     reference.add(userdata).then((value) =>  Get.offAll(LoginPage()));
   }).catchError((onError)=>
       Get.snackbar("Error while creating account ", onError.message),
   );
 }

 void login(String email,String password) async
 {
   await _auth.signInWithEmailAndPassword(email: email, password: password).then((value) => Get.offAll(Dashboard())).
       catchError((onError)=>
   Get.snackbar("Error while sign in ", onError.message));
 }

 void signout() async{
 await _auth.signOut().then((value) => Get.offAll(LoginPage()));

 }


 void sendpasswordresetemail(String email) async{
    await _auth.sendPasswordResetEmail(email: email).then((value) {
      Get.offAll(LoginPage());
      Get.snackbar("Password Reset email link is been sent", "Success");
    }).catchError((onError)=> Get.snackbar("Error In Email Reset", onError.message) );
 }

 void deleteuseraccount(String email,String pass) async{
    User user = await _auth.currentUser;

    AuthCredential credential = EmailAuthProvider.credential(email: email, password: pass);


    await user.reauthenticateWithCredential(credential).then((value) {
      value.user.delete().then((res) {
        Get.offAll(LoginPage());
        Get.snackbar("User Account Deleted ", "Success");
      });
    }

    ).catchError((onError)=> Get.snackbar("Credential Error", "Failed"));
  }

}


Forgot Password.dart

Here i have TextField to enter email and a button when press the sendpasswordresetemail method will be called and email will passed.

then forgot password process starts as above.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login_ui/GetXHelper/FirebaseController.dart';
import 'package:flutter_login_ui/Screen/RegistrationPage.dart';
import 'file:///C:/Android%20Studio%20Stuff/Flutter%20Project/flutter_login_ui/lib/Widgets/SocialSignWidgetRow.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:velocity_x/velocity_x.dart';

class ForgotPassword extends GetWidget<FirebaseController> {

  TextEditingController email = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage("images/assets/backgroundUI.png"),
                        fit: BoxFit.cover
                    )
                ),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(20,40 , 20, 0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        height: 100,
                        width: 100,
                        child: SvgPicture.asset("images/assets/xing.svg")),
                    HeightBox(10),
                    "Reset Password".text.color(Colors.white).size(20).make(),
                    HeightBox(
                        20
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                      child: TextField(
                        controller: email,
                        decoration: InputDecoration(
                          hintText: 'Email',
                          hintStyle: TextStyle(color: Colors.white),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: new BorderRadius.circular(10.0),
                            borderSide: BorderSide(
                                color: Colors.white
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.blue[400]
                              )
                          ),
                          isDense: true,                      // Added this
                          contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                        ),
                        cursorColor: Colors.white,
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    HeightBox(
                        20
                    ),


                    GestureDetector(
                        onTap: (){

                          controller.sendpasswordresetemail(email.text);

                        },
                        child: "Reset Password".text.white.light.xl.makeCentered().box.white.shadowOutline(outlineColor: Colors.grey).color(Color(0XFFFF0772)).roundedLg.make().w(150).h(40)),

                  ],
                ),
              )
            ],
          ),
        ),
        bottomNavigationBar: GestureDetector(
          onTap: (){
            Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>RegistrationPage()));
          },
          child: RichText(text: TextSpan(
            text: 'New User?',
            style: TextStyle(fontSize: 15.0, color: Colors.black),
            children: <TextSpan>[
              TextSpan(
                text: ' Register Now',
                style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 18,
                    color: Color(0XFF4321F5)),
              ),
            ],
          )
          ).pLTRB(20, 0, 0, 15),
        )
    );
  }



}





DeleteAccount.dart

In delete account page we have 2 textfield to enter Email & Password then a button that called deleteaccount method by passing email,password as parameter.

then the delete auth account process will start as above.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login_ui/GetXHelper/FirebaseController.dart';
import 'package:flutter_login_ui/Screen/RegistrationPage.dart';
import 'file:///C:/Android%20Studio%20Stuff/Flutter%20Project/flutter_login_ui/lib/Widgets/SocialSignWidgetRow.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:velocity_x/velocity_x.dart';

class DeleteAccount extends GetWidget<FirebaseController> {

  TextEditingController email = TextEditingController();
  TextEditingController pass = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage("images/assets/backgroundUI.png"),
                        fit: BoxFit.cover
                    )
                ),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(20,40 , 20, 0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        height: 100,
                        width: 100,
                        child: SvgPicture.asset("images/assets/xing.svg")),
                    HeightBox(10),
                    "Delete Account".text.color(Colors.white).size(20).make(),
                    HeightBox(
                        20
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                      child: TextField(
                        controller: email,
                        decoration: InputDecoration(
                          hintText: 'Email',
                          hintStyle: TextStyle(color: Colors.white),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: new BorderRadius.circular(10.0),
                            borderSide: BorderSide(
                                color: Colors.white
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.blue[400]
                              )
                          ),
                          isDense: true,                      // Added this
                          contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                        ),
                        cursorColor: Colors.white,
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    HeightBox(
                        20
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                      child: TextField(
                        controller: pass,
                        decoration: InputDecoration(
                          hintText: 'Password',
                          hintStyle: TextStyle(color: Colors.white),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: new BorderRadius.circular(10.0),
                            borderSide: BorderSide(
                                color: Colors.white
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.blue[400]
                              )
                          ),
                          isDense: true,                      // Added this
                          contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                        ),
                        cursorColor: Colors.white,
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    HeightBox(20),

                    GestureDetector(
                        onTap: (){
                          print("Login Clicked Event");
                          controller.deleteuseraccount(email.text, pass.text);
                        },
                        child: "Delete Account".text.white.light.xl.makeCentered().box.white.shadowOutline(outlineColor: Colors.grey).color(Color(0XFFFF0772)).roundedLg.make().w(150).h(40)),


                  ],
                ),
              )
            ],
          ),
        ),

    );
  }

  void _login() {

    controller.login(email.text, pass.text);
  }

}



 

MVC | Model View Controller | Android MVC Login Example with Validation

0
Model view Controller MVC android example
Model view Controller android example

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will discuss What is Model View Controller (MVC) & Implement an Android Login Validation form using MVC Pattern.

What is MVC – Model View Controller?

An MVC Pattern – stands for MODEL VIEW CONTROLLER, It is a Software Design Pattern, usually used in developing user interfaces.
MVC Architecture pattern is a way how the information or data is been presented to the user & how the user interacts/deals with the data view.
An MVC framework is nearly utilized in all development processes like Web development and portable application like android MVC and IOS MVC.

MVC Architecture Components

It has 3 Components i.e. MODEL-VIEW-CONTROLLER.

  • MODEL
    Here Model is nothing but a data, it directly manages the data, logic and rules of the application.
    A Model is responsible for managing data of an app.
  • VIEW
    A View in MVC is nothing but a UI design, How you can display the data to the USER screen.
    A view means presentation of the data in a particular format.
  • CONTROLLER
    A Controller is typically a piece, which control all the task/event that a user perform, Such as event handling, navigation, Communication between model & view happens in controller in MVC.
    A Controller recieve the input, validate it, & pass the validated input to Model.

Video Tutorial on MVC

#MVCArchitecture

MVC model view Controller architecture pattern android example
MVC model view Controller architecture

Recommended Video to Learn more about MVC

Android MVC Example Tutorial – Login Validation using MVC

So let’s build a simple Login Validation android app by making user of MVC Architecture Pattern android example.

My Final Project Structure,

Android MVC project Structure

So then, Let’s Begin with MVC android example Code

Step 1: Create a new Android Project for MVC Example

Start your Android-Studio and create a new Project to build a simple Login Validation using MVC pattern.

File > New > New Project > Select Empty Activity > Next > Give a name to your project as MVC EXAMPLE > finish.

Step 2: Creating 3 MVC Components Package Folder in your project

So you know that we are here to work and learn about how to implement MVC in android,

We will create 3 package in our android project

  1. Model
  2. View
  3. Controller

Just Checkout above Project Structure we have 3 package, in each package we have 1 – 2 files ( java class or interface ).

How to Create Folder or Package in Android Studio project?
creating package in android studio

Right Click > New > Package
Here Create 3 Package by name Controller, Model, View as you can see in above image.

Step 3: Creating Interface and Classes  and Coding it.

Then, you need to Create some java files in respective Package directory as follow

Android MVC project Structure


In Model Package create 2 files and add the code as below

IUser.java( Interface)

package com.example.mvcexample.Model;

public interface IUser {

    String getEmail();
    String getPassword();
    int isValid();
}

User.java (class)

package com.example.mvcexample.Model;

import android.text.TextUtils;
import android.util.Patterns;


public class User implements IUser{
    private  String email,password;

    public User(String email, String password) {
        this.email = email;
        this.password = password;
    }

    @Override
    public String getEmail() {
        return email;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public int isValid() {
        // 0. Check for Email Empty
        // 1. Check for Email Match pattern
        // 2. Check for Password > 6

        if(TextUtils.isEmpty(getEmail()))
            return  0;
        else if(!Patterns.EMAIL_ADDRESS.matcher(getEmail()).matches())
            return  1;
        else if(TextUtils.isEmpty(getPassword()))
            return 2;
        else if(getPassword().length()<=6)
           return 3;
        else
            return -1;

    }
}


In Controller Package Create 2 files and add the code as below

ILoginController(Interface)

package com.example.mvcexample.Controller;

public interface ILoginController {
    void OnLogin(String email,String Password);
}

LoginController(Class)

package com.example.mvcexample.Controller;

import com.example.mvcexample.Model.User;
import com.example.mvcexample.View.ILoginView;

public class LoginController implements ILoginController {

    ILoginView loginView;

    public LoginController(ILoginView loginView) {
        this.loginView = loginView;
    }

    @Override
    public void OnLogin(String email, String password) {
        User user = new User(email,password);
        int loginCode = user.isValid();
        if(loginCode == 0)
        {
            loginView.OnLoginError("Please enter Email");
        }else  if (loginCode == 1){
            loginView.OnLoginError("Please enter A valid Email");
        } else  if (loginCode == 2)
        {
            loginView.OnLoginError("Please enter Password");
        }else  if(loginCode == 3){
            loginView.OnLoginError("Please enter Password greater the 6 char");
        }
        else {
            loginView.OnLoginSuccess("login Successful");
        }
    }
}


In View Package Create 1 files and add the code as below

ILoginView (Interface)

package com.example.mvcexample.View;

public interface ILoginView {

    void OnLoginSuccess(String message);
    void OnLoginError(String message);
}

So we are done with MVC Architecture for Android, Then Now let’s Work on Simple UI Design.


MainActivity.xml

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

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Login Form"/>

        <EditText
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:hint="Email"/>

        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:hint="Password"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Login"
            android:id="@+id/loginb"/>
    </LinearLayout>

</LinearLayout>

This XML design just had a 2 Edittext for Email & Password and a button for Login Event.

MainActivity.java

package com.example.mvcexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.mvcexample.Controller.ILoginController;
import com.example.mvcexample.Controller.LoginController;
import com.example.mvcexample.View.ILoginView;

public class MainActivity extends AppCompatActivity  implements ILoginView {
    EditText email,password;
    Button loginb;
    ILoginController loginPresenter;

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

        email = (EditText) findViewById(R.id.email);
        password = (EditText)findViewById(R.id.password);

        loginb = (Button) findViewById(R.id.loginb);
        loginPresenter = new LoginController(this);

        loginb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginPresenter.OnLogin(email.getText().toString().trim(),password.getText().toString().trim());
            }
        });
    }

    @Override
    public void OnLoginSuccess(String message) {
        Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void OnLoginError(String message) {
        Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
    }
}

Here in above Code

We have Implemented a Interface ILoginView Which overrides 2 method OnLoginSuccess and OnLoginError, Both of this Simply show a Toast message.

Then

I have Created a Object with LoginController class that Helps us to send user inputed data on button press by using OnLogin method and then it check for Validation return the result if all the User entered field is success or error.

And depending on this result user will get a toast saying success login or some error message.

Conclusion

In this Android tutorial article we learnt what is MVC? & it’s MVC Architecture and we also implemented MVC pattern example in Android app in a form if login Validation.

Referral

Wikipedia MCV – Model View Controller

Recommended Post

Android

RecyclerView with EditText Example + Expense sum calculation

Jetpack Compose tutorial with State management Example

fetch data from database and store in CSV file format android

Flutter

Auto Create Model from JSON file | json model Dart Package

Flutter Dynamic theme change using getX | Dark & Light mode

Flutter Form Validation- Email validate, Password Confirm

Flutter BLoC Pattern Tutorial – Inc & Dec Example

Flutter Firebase Authentication using GetX library – Velocity X

2
Flutter firebase authentication using getx library

Hi Guys,Welcome to Proto Coders Point, In this flutter tutorial we will connect flutter to firebase console project & also implement flutter firebase authentication using getx library.

So Let’s Begin.

VIDEO TUTORIAL 

Create a new Flutter Project & Connect it to Firebase Console Project

  1. Create a new Flutter Project

    OffCourse you need to Create a new Flutter Project – In Recommend you to use Android-Studio as your IDE for Building Flutter Application.

  2. How to Connect Flutter app to Firebase – Android

    Adding/Create a new Project in Firebase Console

    Connecting Flutter to Firebase 1 add project

    Select Platform  –
    I have selected Android, Because this tutorial is only on Android

    Registering your Flutter android to Firebase

    You will find your Flutter android package name under

    project > Android > app > src > main > AndroidManifest.xml

    Copy android package name and paste it into firebase console app registration as soon below.

    adding firebase to your flutter app

     

    Then, Hit Register app
    Firebase will give you a google-services.json file a show below, you need to just download it and paste in your flutter project under
    project > Android > app
    coping google services in app folder of flutter project Last Step add all the dependencies, as guided by Firebase app registration steps
    adding firebase SDK dependencies -minThen after completing all the above task you need to add a flutter plugin dependencies i.e firebase_core:
    and then in flutter main.dart file you need to call  Firebase.initializeApp();  so that your flutter app will call firebase server and your app will get connected to firebase console.
    firebase initializeAppSo Now your Flutter App is been Connect to Firebase Console Project
    It’s time to Start Implementing Flutter Firebase Auth using Flutter Getx Library.

Implementation of Flutter Firebase Authentication using GetX Library

In this project we have designed a Beautiful UI design for Login and Registration page by using VelocityX library

You may download/clone this flutter login & Registration UI from GitHub or check this tutorial for UI design.
GitHub: https://github.com/RajatPalankar8/Flutter_Login_Registration_UI
Website: https://protocoderspoint.com/flutter-login-register-page-ui-design-adobexd-using-velocity-x-library/

So, For this same Flutter UI design we gonna add Flutter Firebase Authentication. So let’s Begin.

Step 1 : Add Required Dependencies

flutter_svg:
velocity_x:
get:
cloud_firestore: ^0.14.1+3
firebase_auth:

Add this all dependencies in pubspec.yaml file under dependencies tag:

flutter_svg: To show svg image in our UI design.
velocity_x: To build UI design much faster.
get: As this Tutorial is on Getx Firbase Auth Example.
cloud_firebase: Need to send register/store user data in Firebase cloud store.
firebase_auth: To send create Auth and Login Auth Request to Flutter Firebase Authentication service.

Step 2: Turn on Authentication service in Firebase Console

Then, now Go to Firebase Console, open your Flutter firebase project and on the left navigation you may see Authentication open, go into it.

There you need to turn on Firebase Email/password Auth.
firebase turn on authentication email passwordStep 3 : Create a Cloud Firestore database

Just go to Cloud Firestore and Hit that Create Database button and then change the Rules to any one can access

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;   // here allow read, write means any one can access your data // which is not the safe method for Real project
    }
  }
}

This is how our registered user data will be store in firebase firestore

So, Now we are done will all the Firebase setup for Flutter registration email, Let’s Check the flutter dart coding.

Step 4: Coding in Flutter Project

Here is the Project Structure with all the dart file.

We have 3 Directorys

  • GetXHelper : Here we have FirebaseController.dart file which will help you to communicate with Firebase Auth and Firestore server.
  • Screen : In the Folder we have 3 Pages
    Login Page
    Registration Page
    Dashboard Page
  • Widgets : This is just Social Sign Row, Because In UI we have Common Google and Facebook SignIN Icons.


Codes

FirebaseController.dart

In below code We have

_auth : that will help us in creating and user login.

firebaseUser : which will help user to keep user logged in into the app whenever user re-open flutter app.

then we have
3 method that will help us in Creating account in Firebase auth, Login in using Firebase auth and signOut the user from app.

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_login_ui/Screen/Dashboard.dart';
import 'package:flutter_login_ui/Screen/LoginPage.dart';
import 'package:get/get.dart';
import 'package:cloud_firestore/cloud_firestore.dart';


class FirebaseController extends GetxController{
   
  FirebaseAuth _auth = FirebaseAuth.instance;

  Rx<User> _firebaseUser = Rx<User>();

  String get user => _firebaseUser.value?.email;

  @override
  void onInit() {
    _firebaseUser.bindStream(_auth.authStateChanges());
  }


  // function to createuser, login and sign out user

 void createUser(String firstname,String lastname,String email,String password) async
 {
   CollectionReference reference = FirebaseFirestore.instance.collection("Users");

   Map<String,String> userdata ={
     "First Name": firstname,
      "Last Name": lastname,
      "Email":email
   };
   
   await _auth.createUserWithEmailAndPassword(email: email, password: password).
   then((value) {

     reference.add(userdata).then((value) =>  Get.offAll(LoginPage()));
   }).catchError((onError)=>
       Get.snackbar("Error while creating account ", onError.message),
   );
 }

 void login(String email,String password) async
 {
   await _auth.signInWithEmailAndPassword(email: email, password: password).then((value) => Get.offAll(Dashboard())).
       catchError((onError)=>
   Get.snackbar("Error while sign in ", onError.message));
 }

 void signout() async{
 await _auth.signOut().then((value) => Get.offAll(LoginPage()));
 }
}

LoginPage.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login_ui/GetXHelper/FirebaseController.dart';
import 'package:flutter_login_ui/Screen/RegistrationPage.dart';
import 'file:///C:/Android%20Studio%20Stuff/Flutter%20Project/flutter_login_ui/lib/Widgets/SocialSignWidgetRow.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:velocity_x/velocity_x.dart';

class LoginPage extends GetWidget<FirebaseController> {

  TextEditingController email = TextEditingController();
  TextEditingController pass = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage("images/assets/backgroundUI.png"),
                        fit: BoxFit.cover
                    )
                ),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(20,40 , 20, 0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        height: 100,
                        width: 100,
                        child: SvgPicture.asset("images/assets/xing.svg")),
                    HeightBox(10),
                    "Login".text.color(Colors.white).size(20).make(),
                    HeightBox(
                        20
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                      child: TextField(
                        controller: email,
                        decoration: InputDecoration(
                          hintText: 'Email',
                          hintStyle: TextStyle(color: Colors.white),
                          enabledBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                            borderSide: BorderSide(
                              color: Colors.white
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: new BorderRadius.circular(10.0),
                            borderSide: BorderSide(
                              color: Colors.blue[400]
                            )
                          ),
                          isDense: true,                      // Added this
                          contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                        ),
                        cursorColor: Colors.white,
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                HeightBox(
                  20
                ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                      child: TextField(
                        controller: pass,
                        decoration: InputDecoration(
                          hintText: 'Password',
                          hintStyle: TextStyle(color: Colors.white),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: new BorderRadius.circular(10.0),
                            borderSide: BorderSide(
                                color: Colors.white
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.blue[400]
                              )
                          ),
                          isDense: true,                      // Added this
                          contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                        ),
                        cursorColor: Colors.white,
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    HeightBox(20),
                    GestureDetector(
                        onTap: (){
                          print("Login Clicked Event");
                          _login();
                        },
                        child: "Login".text.white.light.xl.makeCentered().box.white.shadowOutline(outlineColor: Colors.grey).color(Color(0XFFFF0772)).roundedLg.make().w(150).h(40)),
                    HeightBox(20),
                    "Login with".text.white.makeCentered(),
                    SocialSignWidgetRow()

                  ],
                ),
              )
            ],
          ),
        ),
        bottomNavigationBar: GestureDetector(
          onTap: (){
            Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>RegistrationPage()));
          },
          child: RichText(text: TextSpan(
            text: 'New User?',
            style: TextStyle(fontSize: 15.0, color: Colors.black),
            children: <TextSpan>[
              TextSpan(
                text: ' Register Now',
                style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 18,
                    color: Color(0XFF4321F5)),
              ),
            ],
          )
          ).pLTRB(20, 0, 0, 15),
        )
    );
  }

  void _login() {

    controller.login(email.text, pass.text);
  }

}




RegistrationPage.dart

import 'dart:math';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login_ui/GetXHelper/FirebaseController.dart';
import 'file:///C:/Android%20Studio%20Stuff/Flutter%20Project/flutter_login_ui/lib/Screen/LoginPage.dart';
import 'file:///C:/Android%20Studio%20Stuff/Flutter%20Project/flutter_login_ui/lib/Widgets/SocialSignWidgetRow.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:velocity_x/velocity_x.dart';
import 'package:get/get.dart';

class RegistrationPage extends GetWidget<FirebaseController>{
  final TextEditingController firstn = TextEditingController();
  final TextEditingController lastn = TextEditingController();
  final TextEditingController email = TextEditingController();
  final TextEditingController password = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage("images/assets/backgroundUI.png"),
                        fit: BoxFit.cover
                    )
                ),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(20,40 , 20, 0),
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                          height: 100,
                          width: 100,
                          child: SvgPicture.asset("images/assets/xing.svg")),
                      HeightBox(10),
                      "Registration".text.color(Colors.white).size(20).make(),
                      HeightBox(
                          20
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                        child: TextField(
                          controller: firstn,
                          decoration: InputDecoration(
                            hintText: 'First Name',
                            hintStyle: TextStyle(color: Colors.white),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.white
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: new BorderRadius.circular(10.0),
                                borderSide: BorderSide(
                                    color: Colors.blue[400]
                                )
                            ),
                            isDense: true,                      // Added this
                            contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                          ),
                          cursorColor: Colors.white,
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                      HeightBox(
                          20
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                        child: TextField(
                          controller: lastn,
                          decoration: InputDecoration(
                            hintText: 'Last Name',
                            hintStyle: TextStyle(color: Colors.white),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.white
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: new BorderRadius.circular(10.0),
                                borderSide: BorderSide(
                                    color: Colors.blue[400]
                                )
                            ),
                            isDense: true,                      // Added this
                            contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                          ),
                          cursorColor: Colors.white,
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                      HeightBox(
                          20
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                        child: TextField(
                          controller: email,
                          decoration: InputDecoration(
                            hintText: 'Email',
                            hintStyle: TextStyle(color: Colors.white),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.white
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: new BorderRadius.circular(10.0),
                                borderSide: BorderSide(
                                    color: Colors.blue[400]
                                )
                            ),
                            isDense: true,                      // Added this
                            contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                          ),
                          cursorColor: Colors.white,
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                      HeightBox(
                          20
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                        child: TextField(
                          controller: password,
                          decoration: InputDecoration(
                            hintText: 'Password',
                            hintStyle: TextStyle(color: Colors.white),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.white
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: new BorderRadius.circular(10.0),
                                borderSide: BorderSide(
                                    color: Colors.blue[400]
                                )
                            ),
                            isDense: true,                      // Added this
                            contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                          ),
                          cursorColor: Colors.white,
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                      HeightBox(20),
                      GestureDetector(
                          onTap: RegisterUser,
                          child: "Sign-Up".text.white.light.xl.makeCentered().box.white.shadowOutline(outlineColor: Colors.grey).color(Color(0XFFFF0772)).roundedLg.make().w(150).h(40)),
                      HeightBox(140),
                      "Login with".text.black.makeCentered(),

                     SocialSignWidgetRow()

                    ],
                  ),
                ),
              )
            ],
          ),
        ),
        bottomNavigationBar: GestureDetector(
          onTap: (){
            Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>LoginPage()));
          },
          child: RichText(text: TextSpan(
            text: 'New User?',
            style: TextStyle(fontSize: 15.0, color: Colors.black),
            children: <TextSpan>[
              TextSpan(
                text: ' Login Now',
                style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 18,
                    color: Color(0XFF4321F5)),
              ),
            ],
          )
          ).pLTRB(20, 0, 0, 15),
        )
    );
  }
  void RegisterUser() {

     controller.createUser(firstn.text, lastn.text, email.text, password.text);

  }
}


Dashboard.dart

import 'package:flutter/material.dart';
import 'package:flutter_login_ui/GetXHelper/FirebaseController.dart';

import 'package:get/get.dart';

class Dashboard extends GetWidget<FirebaseController> {


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            RaisedButton(onPressed: (){
             //logout
              controller.signout();
            },child: Text("Sign Out"),)
          ],
        ),
      ),
    );
  }
}

SocialSignWidgetRow.dart

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

class SocialSignWidgetRow extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [

        Container(
          width: 30,
          height: 30,
          child: SvgPicture.asset("images/assets/google.svg"),
        ),
        Container(
          width: 30,
          height: 30,
          child: SvgPicture.asset("images/assets/facebook.svg"),
        ),
      ],
    );
  }
}

InstanceBinding.dart

import 'package:get/get.dart';
import 'GetXHelper/FirebaseController.dart';

class InstanceBinding extends Bindings{
  @override
  void dependencies() {
    // TODO: implement dependencies
    Get.lazyPut<FirebaseController>(() => FirebaseController());
  }

}

IsSignedIN.dart

import 'GetXHelper/FirebaseController.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'Screen/LoginPage.dart';
import 'Screen/Dashboard.dart';

class IsSignedIn extends GetWidget<FirebaseController> {
  @override
  Widget build(BuildContext context) {
    return Obx((){
       return Get.find<FirebaseController>().user!=null ? Dashboard() : LoginPage();
    });
  }
}

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_login_ui/Screen/Dashboard.dart';
import 'package:flutter_login_ui/Screen/LoginPage.dart';
import 'package:flutter_login_ui/Screen/RegistrationPage.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter_login_ui/WelcomePage.dart';
import 'package:flutter_login_ui/isSignedIn.dart';
import 'package:get/get.dart';

import 'InstanceBinding.dart';


void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialBinding: InstanceBinding(),
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      home: IsSignedIn(),
      routes: {
        '/welcome':(context) => WelcomePage(),
        '/login':(context)=> LoginPage(),
        '/reg':(context)=>RegistrationPage(),
        '/dashboard':(context)=>Dashboard(),
      },
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),


    );
  }
}

And We are done your flutter app is now connected with firebase and provides Flutter Firebase auth with Getx and also store user register data to firebase database.