Home Blog Page 75

Flutter Authentication | Flutter Fingerprint Scanner | Local Auth Package

0
Flutter fingerprint scanner authentication local auth
Flutter fingerprint scanner authentication local auth

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will demonstrate on how to implement flutter local_auth library to add fingerprint scanner to your android or iOS apps.

Video Tutorial 

Introduction of Local_Auth Flutter library

This local auth flutter plugin, will help you to perform local, i.e on-device authentication of the user.

By using this library you can add Biometric aithentication to login in your Android or iOS Application.

NOTE: This will work only on android 6.0.

Let’s Start

Flutter Authentication | Flutter Fingerprint Scanner | Local Auth Package

Step 1: Create new Flutter project

I am using android studio as my IDE to build/develop Flutter Apps, you may you any of you favourite IDE like : VSCode

In android Studio : File > New > New Flutter Project  > Finish

Step 2: Adding Local_auth dependencies

Once your new flutter project is ready or you might have opened existing flutter project.

Now, on your left side of your IDE you may see your project structure, under that find pubspec.yaml file where you need to add the local auth dependencie

pubspec.yaml

dependencies:
  local_auth: ^0.4.0+1

As you can see in below screenshot.

adding local auth plugin flutter

Step 3: Adding  USE_FINGERPRINT permission

USE_FINGERPRINT PERMISSION IN ANDROID

In your Flutter Project

android > app > src > main > AndroidManifest.xml

add the below permission

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.app">

  <uses-permission android:name="android.permission.USE_FINGERPRINT"/>  <!-- add this line -->

<manifest> 

as show in below screenshot

adding use finger permission android manifest

USE_FINGERPRINT PERMISSION IN IOS

In your Flutter Project

ios > Runner > Info.plist 

<key>NSFaceIDUsageDescription</key>
<string>Why is my app authenticating using face id?</string>

as shown in below screenshot

adding faceID touchID in flutter ios

Step 4: Flutter Code

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_local_auth/HomePageAuthCheck.dart';
import 'package:local_auth/local_auth.dart';

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

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

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: HomePageAuthCheck(),
    );
  }
}

HomePageAuthCheck.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';

class HomePageAuthCheck extends StatefulWidget {
  @override
  _HomePageAuthCheckState createState() => _HomePageAuthCheckState();
}

class _HomePageAuthCheckState extends State<HomePageAuthCheck> {
  //variable to check is biometric is there or not
  bool _hasBiometricSenson;

  // list of finger print added in local device settings
  List<BiometricType> _availableBiomatrics;


  String  _isAuthorized = "NOT AUTHORIZED";


  LocalAuthentication authentication = LocalAuthentication();

  //future function to check if biometric senson is available on device
  Future<void> _checkForBiometric() async{
    bool hasBiometric;

    try{
      hasBiometric = await authentication.canCheckBiometrics;
    } on PlatformException catch(e)
    {
      print(e);
    }

    if(!mounted) return;

    setState(() {
      _hasBiometricSenson = hasBiometric;
    });
  }

//future function to get the list of Biometric or faceID added into device
  Future<void> _getListofBiometric() async{
    List<BiometricType> ListofBiometric;

    try{
      ListofBiometric = await authentication.getAvailableBiometrics();
    } on PlatformException catch(e)
    {
      print(e);
    }

    if(!mounted) return;

    setState(() {
      _availableBiomatrics  = ListofBiometric;
    });
  }

  ////future function to check is the use is authorized or no
  Future<void> _getAuthentication() async{
    bool isAutherized = false;

    try{
      isAutherized = await authentication.authenticateWithBiometrics(
          localizedReason: "SCAN YOUR FINGER PRINT TO GET AUTHORIZED",
          useErrorDialogs: true,
          stickyAuth: false
      );
    } on PlatformException catch(e)
    {
      print(e);
    }

    if(!mounted) return;

    setState(() {
     _isAuthorized = isAutherized ? "AUTHORIZED" : "NOT AUTHORIZED";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter local Auth Package"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

            Text(" Is BioMetric Available ? : $_hasBiometricSenson"),
            RaisedButton(onPressed: (){
             _checkForBiometric();
            },color:Colors.blue,child: Text("Check",style: TextStyle(color: Colors.white),),),


            Text(" List of Available Biomatric LIST : $_availableBiomatrics"),
            RaisedButton(onPressed: (){
              _getListofBiometric();
            },color:Colors.blue,child: Text("Check List",style: TextStyle(color: Colors.white),),),


            Text(" Is AUTHORIED ? : $_isAuthorized"),
            RaisedButton(onPressed: (){
              _getAuthentication();
            },color:Colors.blue,child: Text("AUTH",style: TextStyle(color: Colors.white),),),
          ],
        ),
      ),
    );
  }
}

then, thus you flutter application is ready with Fingerprint and FaceID authentication.

Explaination of above code and the properties been used.

First of all

I have Created an instance of a class i.e LocalAuthentication, This class is provided in local_auth package, this will help us in getting access to Local Authentication of the device.

LocalAuthentication authentication = LocalAuthentication();

By using this Class instance object we can make use of different properties such as:

  • canCheckBiometrics: This will return true is Biometric sensor is available.
  • getAvailableBiometrics: This will give list of Biometric finger print.
  • authenticationWithBiometrics: This will invoke a pop up, where it will ask you to “Scan for fingerprint/faceID”, then, if the authentication get matched then you are been authorized or you are unauthorized.

autherticationWithBiometrics has some more properties such as

  • localizedReason: Show a Text on the pop dialog box. flutter fingerprint authentication dialog box
  • useErrorDialog: When set to true, will show a proper message on the dailog screen, weather your device have Available Biometric if not then in alert diaolog it will show a message to go to setting to set a new Fingerprint. when no fingerprint authentication added in device
  • stickyAuth: When set to true, whenever you app goes into background and then you return back to app again, the Authentication process will continue again.

Function Created in above to code to check the same

1. To check if device have biometric sensor or not

//future function to check if biometric sensor is available on device
  Future<void> _checkForBiometric() async{
    bool hasBiometric;

    try{
      hasBiometric = await authentication.canCheckBiometrics;
    } on PlatformException catch(e)
    {
      print(e);
    }

    if(!mounted) return;

    setState(() {
      _hasBiometricSenson = hasBiometric;
    });
  }
hasbiometric

This function will return true if device has biometric sensor else false.

2. To get the list of fingerprint added in your local device

//future function to get the list of Biometric or faceID added into device
  Future<void> _getListofBiometric() async{
    List<BiometricType> ListofBiometric;

    try{
      ListofBiometric = await authentication.getAvailableBiometrics();
    } on PlatformException catch(e)
    {
      print(e);
    }

    if(!mounted) return;

    setState(() {
      _availableBiomatrics  = ListofBiometric;
    });
  }
list of finger print available flutter

This will return array list of fingerprint

3. To check fingerprint authentication

////future function to check is the use is authorized or no
 Future<void> _getAuthentication() async{
   bool isAutherized = false;

   try{
     isAutherized = await authentication.authenticateWithBiometrics(
         localizedReason: "SCAN YOUR FINGER PRINT TO GET AUTHORIZED",
         useErrorDialogs: true,
         stickyAuth: false
     );
   } on PlatformException catch(e)
   {
     print(e);
   }

   if(!mounted) return;

   setState(() {
    _isAuthorized = isAutherized ? "AUTHORIZED" : "NOT AUTHORIZED";
   });
 }

This function will invoke a dialog box when user will be asked to touch the fingerprint scanner to get access to further app process.

Flutter app local login using fingerprint scanner, access to app with local finger print authentication

Notes App – To do list app in Flutter – using Provider

0
flutter todo app tutorial using provider app

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial we will discuss on flutter provider,

By using provider in flutter we will develop an simple Notes app or to do list app in flutter.

DEMO

To do list Notes app flutter GIF IMAGE

What is Flutter provider?

A Provider in flutter is a wrapper around Inherited widget to make it easier to use & more reusable.

By using flutter provider instead of manual writting inheritedwidget, you get simplied alocation of resourse & greatly reduce boilerplate over making new class each time when data gets changed.

For Example: If any data gets changed and need to updated into the App UI, then Instead of rebuilding full hierarchy of Widgets, we can simply Update value of Flutter Provider Consumer Widgets.

Learn more about Flutter Provider

Beginner in provider? Have a look at basic of it : https://protocoderspoint.com/flutter-provider-for-beginners-tutorial-with-example/

So let’s begin…

Video Tutorial

Creating Notes/ To do List app using flutter – provider

Step 1: Create a new Flutter Project

Offcourse you need to create new flutter project, In my case i am making use of android studio as my IDE to develop flutter applications.

Step 2: Add required dependencies – Provider library and Slidable library

Then, as we are building Notes app/to do list app in flutter by using Provider class we need to add Provider dependencies in our flutter project.

And then, we also need Slidable  so that using can easily slide the listTile to delete or remove any notes to do.

Slidabe listTile to delete list

slidable listtile flutter to delete list

add this both dependencies in pubspec.yaml file as soon in below screenshot

adding dependencies provider and slidable

Learn more about this plugin library

Provider official Site

Slidable Official Site

Step 3: Create 2 folder in lib directory and create dart files

Then in lib directory of your flutter project, you need to create 2 directory by name

  • model : Will have 2 files : Notes.dart and NotesProvider.dart
  • Screen : Will have 1 file : Home_Screen.dart

Create respective dart files under those folder as shown below

creating directory and files in flutter

Step 4: Source code

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_note_app_provider/models/NotesProvider.dart';
import 'package:flutter_note_app_provider/screens/Home_Screen.dart';
import 'package:provider/provider.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context)=>NotesProviders(),
      child: MaterialApp(
        title: 'Flutter Demo',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: Home_Screen()
      ),
    );
  }
}



Under Model folder

Notes.dart

In Notes Class we have 2 field to hold data i.e title,description and a Constructor.

This class will work and data model to handle them.

class Notes{
  String title;
  String description;

  Notes(this.title,this.description);
}

NotesProviders.dart

In NotesProviders class has a list of type<Notes> where we gonna store all the data the user create to store ToDo List notes.

It has 2 function

addNotes: that will help us to add data to the List of Array notes.

removeNotes: that will help us deleting/removing notes from the List

NoteProvider class is extended with ChangeNotifier because whenever any data is been changed or when user add notes, the data consumer will get notified, for that we make use of  notifyListeners(); to notify all the data consumer.

import 'package:flutter/cupertino.dart';
import 'package:flutter_note_app_provider/models/Notes.dart';
class NotesProviders extends ChangeNotifier {

  //Notes List
 List<Notes> _notes = new List<Notes>();

 List<Notes> get getNotes{
   return _notes;
 }

// function to add data to list of notes 
 void addNotes(String title,String descriptions)
 {
   Notes note = new Notes(title, descriptions);

   _notes.add(note);

    notifyListeners();
 }

 // function to remove or delete notes by using list index position
 void removeNotes(int index)
 {
   _notes.removeAt(index);
   notifyListeners();
 }


}


Screen Folder

Home_Screen.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_note_app_provider/models/Notes.dart';
import 'package:flutter_note_app_provider/models/NotesProvider.dart';
import 'package:provider/provider.dart';
import 'package:flutter_slidable/flutter_slidable.dart';

// ignore: camel_case_types
class Home_Screen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.purple[600],
     appBar: AppBar(
         titleSpacing: 0.0,
       toolbarHeight: 200,
       title: Image.network("https://9to5mac.com/wp-content/uploads/sites/6/2019/11/how-to-quickly-select-move-delete-notes-iphone-ipad-two-finger-tap.jpeg?quality=82&strip=all",fit: BoxFit.cover,)
     ),

      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Consumer<NotesProviders>(
          builder: (context,NotesProviders data,child){
            return data.getNotes.length !=0 ? ListView.builder(
              itemCount: data.getNotes.length,
              itemBuilder: (context,index){
                return CardList(data.getNotes[index],index);
              },
            ): GestureDetector(onTap: (){
              showAlertDialog(context);
            },child: Center(child: Text("ADD SOME NOTES NOW",style: TextStyle(color: Colors.white,),)));
          },
        ),
      ),

      floatingActionButton: FloatingActionButton(onPressed: () {
        showAlertDialog(context);
      },
          backgroundColor: Colors.white,
          child: Icon(Icons.add,color: Colors.black,),
      ),
    );

  }

}

// ignore: must_be_immutable
class CardList extends StatelessWidget {
  final Notes notes;
  int index;

  CardList(this.notes,this.index);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(2.0),
      child:Slidable(
        actionPane: SlidableDrawerActionPane(),
        actionExtentRatio: 0.25,
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(10),
              topLeft: Radius.circular(10),

            )
          ),
          child: ListTile(
           leading: Icon(Icons.note),
              title: Text(notes.title),
            subtitle: Text(notes.description),
            trailing: Icon(Icons.arrow_forward_ios,color: Colors.black26,),
          ),
        ),

        secondaryActions: <Widget>[
          IconSlideAction(
            caption: 'Delete',
            color: Colors.red,
            icon: Icons.delete,
            onTap: (){
              print("HELLO DELETED");
              Provider.of<NotesProviders>(context,listen: false).removeNotes(index);
            }
          ),
        ],
      ),
    );
  }
}

showAlertDialog(BuildContext context) {

  TextEditingController _Title = TextEditingController();
  TextEditingController _Description = TextEditingController();
  // Create button
  Widget okButton = FlatButton(
    child: Text("ADD NOTE"),
    onPressed: () {
      Provider.of<NotesProviders>(context,listen: false).addNotes(_Title.text, _Description.text);
      Navigator.of(context).pop();
    },
  );

  // Create AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text("ADD A NEW NOTE "),
    content: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        TextField(
          controller: _Title,
          decoration: InputDecoration(hintText: "Enter Title"),
        ),
        TextField(
          controller: _Description,
          decoration: InputDecoration(hintText: "Enter Description"),
        ),
      ],
    ),
    actions: [
      okButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}


 

Download the Project from GITHUB 

Flutter Interview Questions and Answers

3
Flutter interview question and answer 2020
Flutter interview question and answer 2020

Hi Guys, Welcome to Proto Coders Point, This article will be on Flutter Technical Interview Questions asked for flutter job profile for fresher. Flutter Developer interview questions and answers for beginners.

So let’s begin with…

flutter job interview

Flutter interview questions for freshers

Job interview image

1. What is Flutter?

Answer: A Flutter is Cross platform development toolkit by Google, which help to deploy on multiple platform like ANDROID,IOS & WEB with single codebase & Flutter gives a greate UI design quality.


2. What are the advantage of flutter app?

Answer:

The most popular advantabe of flutter framework are:

  • Cross-platform development
  • Faster development
  • Good Community Support
  • Live and Hot Reloading feature
  • Minimal code
  • UI focused
  • easy to understand flutter Documentation.

3. What are the type of widget in flutter?

Answer:

In Flutter dart, everything view is an widget.

But Mainly, There are two types of widgets in flutter

  • StateFull Widget.
  • StateLess Widget.

When Flutter Interviewer ask you the above question, then there are many chances they he/she may also ask you the Question 4 i.e.


4. What is the difference between StateFull Widget and StateLess Widget?

Answer:

In StateFull Widget class, Holds state of the widgets & can we rebuilt with state change, by using setState() method;

Whereas, in Stateless Widget as built only once when it been created or when parent changes. (we can’t change stateless widget on data change).


5. How to access screen size in flutter?

This question may come in various kinds, the Interviewer may ask you how to access pixel density in flutter or he might ask you how to access aspect ration in flutter.

Answer:
We can access screen size and other properties like pixel density, aspect ratio etc with the help of MediaQuery.

Syntax:

MediaQuery.of(context).size.width;

MediaQuery.of(context).size.height;

6. What is Provider & How it works?

Answer:

Provider is a simplest way to handle state management.

The Flutter Provider works on a concept of PUB-SUB, Which means there is one provider & multiple Subscriber, Here Subscriber is Consumer.

Wherever any data change occurred, with notifyChangeListener it will get updated to all the consumer.


7. What are the best Editor for Flutter development?

Answer:

The best flutter editor tools make flutter development faster and smooth,

Flutter IDE need some plugin to develop mobile application.

The popular IDE tools for flutter development are :

  • Android Studio.
  • Visual Studio.
  • IntelliJ IDEA
  • IntelliJ IDEA
  • XCode

8. What is pubspec.yaml file?

Answer: The pubspec.yaml file is a crucial configuration file in a Flutter or Dart project. It is used to manage the project’s dependencies, metadata, and other settings.

9. How to access native feature of a platform?

Answer: We can access native feature of a particular platform by making use of Method Channel in flutter.

10. What is Scaffold in Flutter?

In flutter scaffold widgedis a basic material design layout structure. It has various properties like you can implement Appbar, BottomAppBar, FloatingActionButton, Drawer, BottomNavigationBar & much more.

By using Scaffold widget you can easily change the appearance of your flutter app.

11. What is SafeArea flutter?

In Flutter SafeArea Widget is very important widget, That automatically make user interface dynamic, basically SafeArea is simple a padding which simply add a padding depending on the device app is running.

12. What is Flex Flutter?

By using Flex widget in flutter user can alter/change the axis along with it child. Flexible widget are very important to make the flutter application responsive.

13. How do you handle errors in Flutter?

Answer: Error handling in Flutter can be done using try-catch blocks for synchronous code and .catchError or Future.catchError for asynchronous code. Additionally, the Flutter framework provides error widgets and logging mechanisms for uncaught errors.

14. Can you describe the Flutter rendering process?

Answer: Flutter’s rendering process involves three stages: layout, paint, and compositing. During the layout phase, the widget tree is built and sized. In the paint phase, the tree is drawn, and in the compositing phase, layers are combined and rendered on the screen.

15. How do you implement a custom widget in Flutter?

Answer: A custom widget can be created by extending StatelessWidget or StatefulWidget and implementing the build method to define the widget’s UI.

16. How do you optimize the performance of a Flutter app?

Answer: Performance optimization in Flutter includes minimizing widget rebuilds, using const constructors, leveraging lazy loading, optimizing images, and using effective state management techniques.

17. What is the difference between a Future and a Stream in Dart?

Answer: A Future represents a single asynchronous computation that returns a value or an error. A Stream is used for handling a sequence of asynchronous events, delivering multiple results over time.

18. Explain the Navigator and routing in Flutter.

Answer: The Navigator widget manages a stack of Route objects, allowing for navigation between different screens in a Flutter app. Routing can be handled using named routes or by directly pushing and popping routes.

19. How does Flutter handle state management?

Answer: Flutter offers several state management solutions, including setState(), InheritedWidget, Provider, Riverpod, Bloc, Redux, and more. The choice depends on the complexity and requirements of the app.

20. Explain the Flutter widget tree?

Answer: In Flutter, everything is a widget. Widgets are the basic building blocks of a Flutter app’s UI. The widget tree is a hierarchy of widgets that determines the UI’s layout.

21. What is an InheritedWidget?

Answer: An InheritedWidget is a base class for widgets that efficiently propagate information down the widget tree. It is used to share data between widgets in the widget tree.


5 Best coding books for beginners

Easiest way to create splash screen in flutter

0
Creating Splash Screen in Flutter
Creating Splash Screen in Flutter

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will implement Easiest way to create splash screen in flutter

What is Splash Screen?

In any Mobile or Web Application a Splash Screen is the first screen that is visible to the user when it app is been launched… Usually Splash Screen are used to show company logo and then launch the main screen of the application after some time.

Easiest way to create splash screen in flutter

The Logic behind showing Splash Screen in app.

We are going to make use of Future.delayed method in flutter to load Main page after few seconds

Here is a snippet code

@override
 void initState() {
  
   Future.delayed(Duration(seconds:3),(){
     print("After 3 seconds");

     //This block of code will execute after 3 sec of app launch
     Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>MyHomePage()));
   });

   super.initState();
 }

In Flutter Class that extends StateFull widget, we are going to make use of an override function i.e initState().

Inside initState function we gonna call Future.delayed() that gets execute after few seconds.

Then, as you can see in above Snippet code Duration is set with 3 secs.

So, the Inner statement get loaded after 3 seconds.

Splash Screen in Flutter ( Source code )

Video Tutorial

Project Structure

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_splash/Splash_Screen.dart';

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

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

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: SplashScreen(),  //calling Splash Screen page
    );
  }
}


SplashScreen.dart

import 'package:flutter/material.dart';
import 'package:flutter_splash/MyHomePage.dart';

class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {

  @override
  void initState() {
    // TODO: implement initState
    Future.delayed(Duration(seconds:100),(){
      print("After 3 seconds");

      Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>MyHomePage()));
    });

    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: FlutterLogo(
              size: 200,
              colors: Colors.pink,
            ),
          ),
        ],
      ),
    );
  }
}

MyHomePage.dart

import 'package:flutter/material.dart';

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("This is Home page After Splash Screen"),
      ),
    );
  }
}

 

Similar Articles

https://protocoderspoint.com/flutter-splash-screen-example-with-loading-animation-using-spinkit-library/