Home Blog Page 73

Login With Email / Username / Phone using one TextField – Flutter GetX State Management

0
Login With Email Username Phone Number using one TextField - Flutter GetX StateManagement
Login With Email Username Phone Number using one TextField - Flutter GetX StateManagement

Hi Guys, Welcome to Proto Coders Point,
In this flutter tutorial we will create a Flutter Login/SignIn form:
Which will have 1 Textfield to handle Email login, Username login, or Phone Number login Authentication method.

So let’s begin with the task

Single TextField to login with Email, Username, phoneno – using Flutter GetX State Management

Video Tutorial

Watch our Flutter Tutorial of GetX to validate one textfield for multiple signIn auth methods.

So let’s begin with the project task

Step 1: Create a new Flutter project

I choice android-studio to build flutter apps, you can make your of your favorite IDE to build Flutter application

In Android studio, Create a new flutter project, give it a good name and finish it , your flutter project will get ready with some default code.

Step 2: Add GETX dependencies

In your Flutter project structure you may see a file by name pubspec.yaml file, open it then, under dependencies you need to add getx flutter library.

Get the latest version of flutter getx library from official site : https://pub.dev/packages/get

As you can see in below screenshot with high lighted: follow it if you have confussion.

how to add getx dependencies in flutter project

Step 3: Create a new Folder and dart file (GetXHelper)

In Lib directory of your flutter project and create a new folder in it

Right Click  lib > New > Package

Give a name to this Package/ folder, as you can see in below screenshot i have named it as GetXPackage

Under GetXPackage folder create new dart file by name GetXHelper.dart

Right Click on GetXPackage folder > New > Dart File

Step 4: Coding for GetXHelper class

GetXHelper.dart

import 'package:get/get.dart';

class GetXHelper extends GetxController{

  int which = 0;

  void checktext(String text)
  {
    if(text.isNum)
      {
        print("${text} is a number");
        which = 1;
      }else if(text.isAlphabetOnly)
        {
          print("${text} is a username");
          which = 2;
        }else if(text.isEmail)
          {
            print("${text} is Email");
            which = 3;
          }
    else if(text.isEmpty)
      {
        which = 0;
      }

    update();
  }

  void login()
  {
    if(which == 1)
      {
        //auth
        print("Run a method from phone number signIn");
      }
    else if(which == 2)
      {
        print("Run a method from Username signIn");
        //auth
      }
    else if(which == 3)
      {
        print("Run a method from Email signIn");//auth

      }
    else{
      print("Show a message to user if textfield is empty");

    }
  }
}

Here in above code we have 2 methods of GetX class

  • CheckText(String text): 

    This Method will check if the user entered text is a number, a username or a Email, and depending of used entered text we will set a value to a variable,
    Eg: int which =  0 ;If “which” is 0 then user has not entered text yet.
    If “which” is 1 then user has entered a phone number(number).
    Then like wise if user entered username then “which” will be set to 2 and if user entered email then which vairable will be set to 3.

  • Login(): Now In login method we have if else if statement, depending of the value of which variable we can run different authentication eventsFor example: if which == 3 then email authentcation will get run
        and if which == 1 then phone number signIn method will run 

Step 4: UI Design main.dart

import 'package:flutter/material.dart';
import 'package:flutter_textfield_signin/GetXPackage/GetXHelper.dart';
import 'package:get/get.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: LoginScreen(),
    );
  }
}
class LoginScreen extends StatelessWidget {

  TextEditingController email = TextEditingController();
  TextEditingController pass = TextEditingController();

  // Creating a Object by using GetXHelper Class and injection it in main.dart class so that  you can use getXHelper to call and pass use entered data
  final GetXHelper getXHelper = Get.put(GetXHelper());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Login Page"),
      ),
      body: Column(
         mainAxisAlignment: MainAxisAlignment.center,
       children: [
         Padding(
           padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
           child: TextField(
             onChanged: (text)
             {
               // When user enter text in textfield getXHelper checktext method will get called
               getXHelper.checktext(text);
             },
             controller: email,
             decoration: InputDecoration(
               hintText: 'Email | PhoneNo | Username',
               hintStyle: TextStyle(color: Colors.grey),
               enabledBorder: OutlineInputBorder(
                 borderRadius: new BorderRadius.circular(10.0),
                 borderSide: BorderSide(
                     color: Colors.black
                 ),
               ),
               focusedBorder: OutlineInputBorder(
                   borderRadius: new BorderRadius.circular(10.0),
                   borderSide: BorderSide(
                       color: Colors.blue
                   )
               ),
               isDense: true,                      // Added this
               contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
             ),
             cursorColor: Colors.black,
             style: TextStyle(color: Colors.black),
           ),
         ),
         SizedBox(
           height: 20,
         ),

         GetBuilder<GetXHelper>(builder: (_){

           return _.which == 1 ? Container() :  Padding(
             padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
             child: TextField(

               controller: pass,
               decoration: InputDecoration(
                 hintText: 'Password',
                 hintStyle: TextStyle(color: Colors.grey),
                 enabledBorder: OutlineInputBorder(
                   borderRadius: new BorderRadius.circular(10.0),
                   borderSide: BorderSide(
                       color: Colors.black
                   ),
                 ),
                 focusedBorder: OutlineInputBorder(
                     borderRadius: new BorderRadius.circular(10.0),
                     borderSide: BorderSide(
                         color: Colors.blue
                     )
                 ),
                 isDense: true,                      // Added this
                 contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
               ),
               cursorColor: Colors.black,
               style: TextStyle(color: Colors.black),
             ),
           );

         }),

         RaisedButton(
           color: Colors.blue,
           onPressed: () {
             // call login method
             getXHelper.login();
           },
           child: Text("LOGIN"),
         ),
       ],
      ),
    );
  }
}


Creating a Object by using GetXHelper Class and injection it in main.dart class so that you can use getXHelper to call and pass user entered data.

When user enter text in textfield getXHelper checktext method will get called, and this method will check if user enter text is Phone, username or Email.

 

 

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