Home Blog Page 73

Flutter Encryption and Decryption using flutter string encryption

0
how to encrypt password in flutter
how to encrypt password in flutter

Hi Guys Welcome to Proto Coders Point, In this Flutter tutorial we will check how to encrypt password in flutter using flutter string encryption.

Video Tutorial

Flutter string encryption Package Plugin

This package is very useful for string encryption, it’s a Cross platform string encryption which uses commonly best Encrytion methods like (AES/CBC/PKCS5/RandomIVs/HMAC-SHA256 Integrity Check).

Installation of Flutter Encryption package

1. Adding Dependencies in pubspec.yaml file

open your flutter project that you have created in your IDE(android-studio).

In your project structure you may see a file by name pubspec.yaml name open, in this file under dependencies add the package

dependencies:
  flutter_string_encryption: ^0.3.1   // add this line // package version may change kindly check update version on offical site

2. Importing the package

Then after you have added the required flutter encryption package now you need to import the package where you will be using it in your code to encrypt or decrypt the string or the password the user enter.

import 'package:flutter_string_encryption/flutter_string_encryption.dart';

So now the flutter encryption and decryption package is been successfully added into your flutter project, now you can use it.

So now let’s check how to encrypt a string using flutter string encryption

Usage of the library

// create a PlatformStringCryptor

In Below Snippet code we have creating an object of PlatformStringCryptor that will help use in creatng salt and to generate key.

final cryptor = new PlatformStringCryptor();

// generate a Salt string using Cryptor

final String salt = await cryptor.generateSalt();

//generate a key from password

Here password is the text that user enter in textfield

final String key = await cryptor.generateKeyFromPassword(password, salt);

Encrypt A String

final String encrypted = await cryptor.encrypt("Password that you want to encrypt", key);

Decrypt A String

try {
  final String decrypted = await cryptor.decrypt(encrypted, key);
  print(decrypted); // - A string to encrypt.
} on MacMismatchException {
  // unable to decrypt (wrong key or forged data)
}

IMPORTANT NOTE

Then key that is used to Encrypt a string should be same while you want to decrypt the encrypted string.

Implementing Flutter Encryption decryption in Flutter Project

main.dart

import 'dart:math';

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


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

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

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {

  TextEditingController pass = TextEditingController();

  var key = "null";
  String encryptedS,decryptedS;

  var password = "null";

  PlatformStringCryptor cryptor;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Password Encrypt"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
              child: TextField(
                controller: pass,
                decoration: InputDecoration(
                  hintText: 'Password',
                  hintStyle: TextStyle(color: Colors.black),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: new BorderRadius.circular(10.0),
                    borderSide: BorderSide(
                        color: Colors.red
                    ),
                  ),
                  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,
              ),
            ),
            RaisedButton(
              onPressed: (){
                Encrypt();
              },
              child: Text("Encrypt"),
            ),
            RaisedButton(
              onPressed: (){
                Decrypt();
              },
              child: Text("Decrypt"),
            ),
          ],
        ),
      ),
    );
  }

// method to Encrypt String Password
  void Encrypt() async{

    cryptor = PlatformStringCryptor();
    final salt = await cryptor.generateSalt();

    password = pass.text;

    key = await cryptor.generateKeyFromPassword(password, salt);

  // here pass the password entered by user and the key
    encryptedS = await cryptor.encrypt(password, key);

    print(encryptedS);
  }


// method to decrypt String Password
  void Decrypt() async{

    try{
      //here pass encrypted string and the key to decrypt it 
      decryptedS = await cryptor.decrypt(encryptedS, key);

      print(decryptedS);
    }on MacMismatchException{

    }
  }

}


Output

Flutter encrypted decrypted example
Flutter encrypted decrypted example

 

Arrays in Dart – How to create & print array in flutter / dart?

0
How to print array in flutter
How to print array in flutter

Hi Guys, Welcome to Proto Coders Point, In this tutorial we will learn about arrays in dart flutter with an example

What is array in dart?

Same as other programming language, In dart also the defination of array is same.

An array in an object that can be used to store a list of collections of elements. In array list the collection can be of any datatype: numbers, String, etc.

In Flutter dart, array can be used to store multiple values in one datatype variable.

To access the value/element in the array list then you can do it through it index id.
The value stored in an array are called as elements.

array in dart flutter
array structure in dart flutter

Initializing arrays in Dart

Using literal constructor

Using Literal constructor [] an new array can be created: as shown in below example:

import 'dart:convert';
void main() { 
   var arr = ['a','b','c','d','e'];  // array literal constructor

   print(arr);    //print the array on the screen 
}

How to print array in flutter?

To print array list on the screen or on console log then

you can make use of print cmd to print on console

else if you want to display array in your flutter app then you can make use of Text widget to show the array list

 new keyword and List 

import 'dart:convert';
void main() { 
   var arr = new List(5);// creates an empty array of length 5
   // assigning values to all the indices


   //adding data to array list 
   arr[0] = 'a'; 
   arr[1] = 'b'; 
   arr[2] = 'c'; 
   arr[3] = 'd'; 
   arr[4] = 'e';  


   print(arr); 
}

How to access particular array element? Method to read array list

first() Return first element of the array.
last()  last element of the array.
isEmpty() It returns true if the list is empty; otherwise, it returns false.
length() It returns the length of the array. eg : 5

Example

import 'dart:convert';
void main() { 
   var arr = ['a','b','c','d','e']; 
   print(arr.first);// first element of array
   print(arr.last);// last element of array
   print(arr.isEmpty);// to check whether the array is empty or not
   print(arr.length);// the lenght of the array
   
}

Recommended Article

Dart data types – variable in dart

Flutter array array in flutter

Dropdown in flutter

List in dart – convert list to set or vice versa

Why flutter hot reload is  faster then gradle build android instant run?

1
why flutter hot reload is fast
why flutter hot reload is fast

Hi Guys, Welcome to Proto Coders Point.

In this article we will discuss on why flutter hot reload is faster then android instant run.

Very little difference you may see in flutter hot reload and android Instant run/gradle build

Flutter Hot Reload

The Flutter Framework automatically rebuilds the widget tree, this framework allow you to rapidly boost and reload the changes that your have made in your source code.

When you change flutter dart code and save and send your dart code to get rebuild in your mobile phone where it takes only few seconds or sometime instantly get run.

Hot reload in flutter is so fast because Flutter engine make user of JIT model (just-in_time) for compilation while you run in debug mode, which means that less time is spent in compilation.

But at some point of time, you have to reload/restart your flutter dart code with re-initializes the app’s state

In development mode, Flutter is compiled just-in-time. That is why we can do hot-reload/restart so fast. In release mode (when you go to publish your app), your code is compiled ahead-of-time, to native code. It is for better performace, minimum size and remove other stuff that are useful in dev mode.

What is different between hot reload, hot restart and full restart?

Hot reload: Here it only re build the widget tree where changes has occurred, keeping the app state as it was before hot reload, this does not re run the main() or the initState() of the dart code.

Hot Restart: This will restarts the flutter dart code and it also forget and rebuild the app state, all the previous app state will get lost when hot restart is preformed.

Full restart: In flutter full restart it recompile full project source code for ios, Android, Web that why it may take some longer time because it need to compile the java/Kotlin/objC and swift code etc.

Android Instant run

In android studio instant run same a flutter reload but instant run will always compiles the class fully.

Instant run the VM will checks if a new class change is been made.

Android Studio  instant run will try it’s best to change as little as possible, if it can change some part of classes then it will, but it often needs to replace the entire activity and sometimes the entire app will get rebuilt.

Recommended Flutter Articles

Pros of Flutter. Why flutter app development is best?

Future of Flutter app development

Why is Flutter trending in 2021

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: