Home Blog Page 21

MVVM architecture in flutter app example using provider

0
flutter mvvm
flutter mvvm architecture

Model-View-ViewModel is referred to as MVVM.

The fundamental concept is to build a view model that feeds information to the view. The view model’s data can be used by the view to fill itself with information. Writing modular code that can be used by multiple views is made possible by the creation of a view-model layer.

Why is MVVM required in flutter?

As far as we are aware, flutter does not support any kind of development architecture. This implies that it must be implemented by developers.

Since MVVM allows you to hold all of your business logic inside the ViewModel class and separate from the UI, it easily demonstrates the need for an architecture to communicate between the UI & business logic.


What is MVVM Flutter?

Model, View, and ViewModel are the three main elements that control MVVM (Model-View-ViewModel).

The key components make it easier to set up a foundation for the MVVM design pattern. Each component has a variety of functions and responsibilities, and a crucial part in the development of the application is played by the key components’ well-founded interactions with one another.

The ViewModel and View interact with each other for data binding in the MVVM architecture. The ViewModel is used to communicate with the model.


Advantages of MVVM architecture

  • MVVM facilitates easier parallel development of a UI and the building blocks that power it
  • MVVM abstracts the View and thus reduces the quantity of business logic (or glue) required in the code behind it. 
  • The ViewModel can be easier to unit test than in the case of event-driven code.

Business logic can be moved from views to viewmodels and models using MVVM. ViewModel serves as a bridge between the view and the model, transferring all user events and returning the outcome.


MVVM (Model-View-ViewModel)

Model

This layer is in charge of transferring data to the ViewModel from the server or a local database.

We define the Network, Local DB, and Repository in this layer so that API, DB, etc. can be communicated with.

ViewModel

Data is transferred between View and Model using ViewModel, which also accepts all user events and asks the Model to respond with data. Once the Model has the data, it goes back to the ViewModel, which then notifies the View of the information.

A single ViewModel can supply data to multiple Views because it can be used by multiple views.

View

The view is the area of the screen where the user interacts with the Widgets displayed there. These user events call for a few actions that direct users to the ViewModel, where the rest of the ViewModel completes the task. ViewModel updates View once it has the necessary data.

We’ll now walk through an example that shows how the MVVM architecture works, using the Provider state mechanism to notify data.

We will now see an example that shows how the MVVM architecture works. To notify data, we will use the Provider, and to make server requests, we will use the HTTP package.

The request is also completed using a repository layer, and the data is then returned to the view through the viewmodel.


MVVM Architecture :

Our MVVM architecture is shown below, and I’m now going to explain the folder structure so that you can understand what should be done as MVVM best practices.

Directory structure

models: For a clean architecture, create inner directories for each API response model class in this directory, which will house all of the model classes for the API response.

view: For the project, this directory will house all the classes related to views, along with subdirectories for each module and widget.

view model: This directory, which optionally includes subdirectories, will house all ViewModel-related classes.


Benefits Of MVVM Architecture For iOS And Android Apps

The primary goal of the mobile app architecture pattern in app development is to support the mobile app development strategies with a broad range of techniques based on vendor- and industry-specific standards that ultimately enhance the creation of the app, whether it be for Android or iOS. Why MVVM is important for your app is a question that most project owners find uncomfortable to answer. In other words, the question makes the claim that “your app can do wonders with this design pattern.”

The Model View ViewModel (MVVM), an acronym for Model View ViewModel, aims to divide the application into three logical components and then handle particular app development aspects. Although the market is flooded with architectural patterns that enhance device capabilities and application performance, the MVVM specifically emphasises the significance of solution architecture in levying a better user interface (UI) experience. The MVVM architecture has many advantages in addition to managing and displaying data objects, some of which are listed below.


Flutter MVVM with provider

Let’s get to the coding part

We must use the ChangeNotifierProvider, a component of the Provider package, to notify the view of the updated MoviesListVM. As shown below, add the dependency for the provider package in the pubspec.yaml file.

Http : ^any
Provider: ^any

Service.dart

This generic class interacts with the ViewModel via a repository class and manages all network requests.

@override
Future getResponse(String url) async {
 dynamic responseJson;
 try {
   final response = await http.get(Uri.parse(mediaBaseUrl + url));
   responseJson = returnResponse(response);
 } on SocketException {
   throw FetchDataException('Oops , No Internet ');
 }
 return responseJson;
}

@visibleForTesting
dynamic returnResponse(http.Response response) {
 switch (response.statusCode) {
   case 200:
     dynamic responseJson = jsonDecode(response.body);
     return responseJson;
   case 400:
     throw BadRequestException(response.body.toString());
   case 401:
   case 403:
     throw UnauthorisedException(response.body.toString());
   case 500:
   default:
     throw FetchDataException(
         'Error occurwhile with server with status code : ${response.statusCode}');
 }
}

Repository

This layer of the repository is in charge of interacting with the network layer and transferring data to the ViewModel class as needed.

BaseService _service = Service();

Future<List<Media>> fetchMediaList(String value) async {
 dynamic response = await _service.getResponse(value);
 final jsonData = response['results'] as List;
 List<Media> mediaList =
     jsonData.map((tagJson) => Media.fromJson(tagJson)).toList();
 return mediaList;
}

ViewModel.dart

ApiResponse _apiResponse = ApiResponse.initial('Empty data');

Media? _media;

ApiResponse get response {
 return _apiResponse;
}

Media? get media {
 return _media;
}

/// Call the media service and gets the data of requested media data of an artist.
Future<void> fetchMediaData(String value) async {
 _apiResponse = ApiResponse.loading('Fetching artist data');
 notifyListeners();
 try {
   List<Media> mediaList = await Repository().fetchMediaList(value);
   _apiResponse = ApiResponse.completed(mediaList);
 } catch (e) {
   _apiResponse = ApiResponse.error(e.toString());
   print(e);
 }
 notifyListeners();
}

void setSelectedMedia(Media? media) {
 _media = media;
 notifyListeners();
}

HomePage.dart

Widget getMediaWidget(BuildContext context, ApiResponse apiResponse) {
 List<Media>? mediaList = apiResponse.data as List<Media>?;
 switch (apiResponse.status) {
   case Status.LOADING:
     return Center(child: CircularProgressIndicator());
   case Status.COMPLETED:
     return Column(
       mainAxisSize: MainAxisSize.min,
       children: [
         Expanded(
           flex: 8,
           child: PlayerListWidget(mediaList!, (Media media) {
             Provider.of<ViewModel>(context, listen: false)
                 .setSelectedMedia(media);
           }),
         ),
         Expanded(
           flex: 2,
           child: Align(
             alignment: Alignment.bottomCenter,
             child: PlayerWidget(
               function: () {
                 setState(() {});
               },
             ),
           ),
         ),
       ],
     );
   case Status.ERROR:
     return Center(
       child: Text('Please try again latter!!!'),
     );
   case Status.INITIAL:
   default:
     return Center(
       child: Text('Search the song by Artist'),
     );
 }
}

@override
Widget build(BuildContext context) {
 final _inputController = TextEditingController();
 ApiResponse apiResponse = Provider.of<ViewModel>(context).response;
 return Scaffold(
   appBar: AppBar(
     title: Text('Media Player'),
   ),
   body: Column(
     children: <Widget>[
       Padding(
         padding: const EdgeInsets.symmetric(vertical: 10.0),
         child: Row(
           children: <Widget>[
             Expanded(
               child: Container(
                 margin: EdgeInsets.symmetric(horizontal: 20.0),
                 decoration: BoxDecoration(
                   color: Theme.of(context).accentColor.withAlpha(50),
                   borderRadius: BorderRadius.circular(30.0),
                 ),
                 child: TextField(
                     style: TextStyle(
                       fontSize: 15.0,
                       color: Colors.grey,
                     ),
                     controller: _inputController,
                     onChanged: (value) {},
                     onSubmitted: (value) {
                       if (value.isNotEmpty) {
                         Provider.of<ViewModel>(context, listen: false)
                             .setSelectedMedia(null);
                         Provider.of<ViewModel>(context, listen: false)
                             .fetchMediaData(value);
                       }
                     },
                     decoration: InputDecoration(
                       border: InputBorder.none,
                       enabledBorder: InputBorder.none,
                       focusedBorder: InputBorder.none,
                       prefixIcon: Icon(
                         Icons.search,
                         color: Colors.grey,
                       ),
                       hintText: 'Enter Artist Name',
                     )),
               ),
             ),
           ],
         ),
       ),
       Expanded(child: getMediaWidget(context, apiResponse)),
     ],
   ),
 );
}

Response.dart

Status status;
T? data;
String? message;

Response.initial(this.message) : status = Status.INITIAL;

Response.loading(this.message) : status = Status.LOADING;

Response.completed(this.data) : status = Status.COMPLETED;

Response.error(this.message) : status = Status.ERROR;

@override
String toString() {
 return "Status : $status \n Message : $message \n Data : $data";
}

This enum manages various UI section states, such as loading, completed, and error.

enum Status { 
INITIAL,
LOADING,
COMPLETED,
ERROR
 }

MVVM and MVC architecture differences

The key distinctions between MVVM and MVC are listed below.

Difference between mvc and mvvm
MVVM (Model View ViewModel)MVC (Model View Controller)
The view serves as the Application’s front door.The Controller is where the Application starts.
View and Viewmodel relationships are one to many.Controller and view relationships are one to many.
Views make use of the View-Model.View Has no connection to the Controller
MVVM is a fairly recent model.Old Model MVC
When we have intricate data bindings, debugging will be challenging.This Model is challenging to read, modify, unit test, and reuse.
MVC Model components may undergo independent testing from users.The code is event-driven and simple for independent unit testing.

Conclusion

I explained the basic structure of the MVVM architecture in a flutter in the article; you can modify this code to suit your needs. This was my brief introduction to Effect On User Interaction, and it works with Flutter.

I hope this blog has given you enough information to try out the MVVM architecture in your flutter projects. We will demonstrate what the Introduction is. Nowadays, MVVM is widely used because it supports an event-driven approach, which is essential because many flutter components operate based on events.

Here you can find the complete repository code , click here

https://github.com/Mitali8620/flutter_MVVM.git

Thank you for taking the time to read this 🙂 Have a Happy day……..

Drawing INDIAN FLAG using Python Turtle

0
Draw INDIAN FLAG in Python using Turtle module

To draw a Indian Flag using Python langauge we will make use of Python Turtle module/library.

Function used from Turtle Graphics:

  • forward(x): moves the pen in forward direction by x units.
  • backward(x): moves the pen in the backward direction by x units.
  • right(x): rotate the pen in the clockwise direction by an angle x.
  • left(x): rotate the pen in the anticlockwise direction by an angle x.
  • penup(): stop drawing of the turtle pen.
  • pendown(): start drawing of the turtle pen.
  • begin_fill(): starts filling the color inside the shape.
  • fillcolor(“color_name”): sets the color to be filled.
  • end_fill(): stops filling the color.

Complete Source Code to draw INDIAN FLAG using Python Turtle

indianFlag.py

import turtle
from turtle import*

#screen for output
screen = turtle.Screen()

# Defining a turtle Instance
t = turtle.Turtle()
speed(0)

# initially penup()
t.penup()
t.goto(-400, 250)
t.pendown()

# Orange Rectangle
#white rectangle
t.color("orange")
t.begin_fill()
t.forward(800)
t.right(90)
t.forward(167)
t.right(90)
t.forward(800)
t.end_fill()
t.left(90)
t.forward(167)

# Green Rectangle
t.color("green")
t.begin_fill()
t.forward(167)
t.left(90)
t.forward(800)
t.left(90)
t.forward(167)
t.end_fill()

# Big Blue Circle
t.penup()
t.goto(70, 0)
t.pendown()
t.color("navy")
t.begin_fill()
t.circle(70)
t.end_fill()

# Big White Circle
t.penup()
t.goto(60, 0)
t.pendown()
t.color("white")
t.begin_fill()
t.circle(60)
t.end_fill()

# Mini Blue Circles
t.penup()
t.goto(-57, -8)
t.pendown()
t.color("navy")
for i in range(24):
	t.begin_fill()
	t.circle(3)
	t.end_fill()
	t.penup()
	t.forward(15)
	t.right(15)
	t.pendown()
	
# Small Blue Circle
t.penup()
t.goto(20, 0)
t.pendown()
t.begin_fill()
t.circle(20)
t.end_fill()
# Spokes
t.penup()
t.goto(0, 0)
t.pendown()
t.pensize(2)
for i in range(24):
	t.forward(60)
	t.backward(60)
	t.left(15)
	
#to hold the
#output window
turtle.done()

How to Draw a Batman Logo using Python Turtle

0
Draw BATMAN Logo in Python using Turtle module
batman logo using python

batman.py

import turtle
import math

kalam = turtle.Turtle()
kalam.speed(500)

window = turtle.Screen()
window.bgcolor("#000000")
kalam.color("white")

ankur = 20

kalam.left(90)
kalam.penup()
kalam.goto(-7 * ankur, 0)
kalam.pendown()

for a in range(-7 * ankur, -3 * ankur, 1):
    x = a / ankur
    rel = math.fabs(x)
    y = 1.5 * math.sqrt((-math.fabs(rel - 1)) * math.fabs(3 - rel) / ((rel - 1) * (3 - rel))) * (
                1 + math.fabs(rel - 3) / (rel - 3)) * math.sqrt(1 - (x / 7) ** 2) + (
                    4.5 + 0.75 * (math.fabs(x - 0.5) + math.fabs(x + 0.5)) - 2.75 * (
                        math.fabs(x - 0.75) + math.fabs(x + 0.75))) * (1 + math.fabs(1 - rel) / (1 - rel))
    kalam.goto(a, y * ankur)

for a in range(-3 * ankur, -1 * ankur - 1, 1):
    x = a / ankur
    rel = math.fabs(x)
    y = (2.71052 + 1.5 - 0.5 * rel - 1.35526 * math.sqrt(4 - (rel - 1) ** 2)) * math.sqrt(
        math.fabs(rel - 1) / (rel - 1))
    kalam.goto(a, y * ankur)

kalam.goto(-1 * ankur, 3 * ankur)
kalam.goto(int(-0.5 * ankur), int(2.2 * ankur))
kalam.goto(int(0.5 * ankur), int(2.2 * ankur))
kalam.goto(1 * ankur, 3 * ankur)
print("Batman Logo with Python Turtle")
for a in range(1 * ankur + 1, 3 * ankur + 1, 1):
    x = a / ankur
    rel = math.fabs(x)
    y = (2.71052 + 1.5 - 0.5 * rel - 1.35526 * math.sqrt(4 - (rel - 1) ** 2)) * math.sqrt(
        math.fabs(rel - 1) / (rel - 1))
    kalam.goto(a, y * ankur)

for a in range(3 * ankur + 1, 7 * ankur + 1, 1):
    x = a / ankur
    rel = math.fabs(x)
    y = 1.5 * math.sqrt((-math.fabs(rel - 1)) * math.fabs(3 - rel) / ((rel - 1) * (3 - rel))) * (
                1 + math.fabs(rel - 3) / (rel - 3)) * math.sqrt(1 - (x / 7) ** 2) + (
                    4.5 + 0.75 * (math.fabs(x - 0.5) + math.fabs(x + 0.5)) - 2.75 * (
                        math.fabs(x - 0.75) + math.fabs(x + 0.75))) * (1 + math.fabs(1 - rel) / (1 - rel))
    kalam.goto(a, y * ankur)

for a in range(7 * ankur, 4 * ankur, -1):
    x = a / ankur
    rel = math.fabs(x)
    y = (-3) * math.sqrt(1 - (x / 7) ** 2) * math.sqrt(math.fabs(rel - 4) / (rel - 4))
    kalam.goto(a, y * ankur)

for a in range(4 * ankur, -4 * ankur, -1):
    x = a / ankur
    rel = math.fabs(x)
    y = math.fabs(x / 2) - 0.0913722 * x ** 2 - 3 + math.sqrt(1 - (math.fabs(rel - 2) - 1) ** 2)
    kalam.goto(a, y * ankur)

for a in range(-4 * ankur - 1, -7 * ankur - 1, -1):
    x = a / ankur
    rel = math.fabs(x)
    y = (-3) * math.sqrt(1 - (x / 7) ** 2) * math.sqrt(math.fabs(rel - 4) / (rel - 4))
    kalam.goto(a, y * ankur)

kalam.penup()
kalam.goto(300, 300)
turtle.done()

How to Draw an Ironman Helmet using Python Turtle

0
Draw IRONMAN Helmet in Python using Turtle
IRONMAN Helmet
drawing ironman mask using python
drawing ironman mask using python

ironman.py

import turtle

ankur1 = [[(-40, 120), (-70, 260), (-130, 230), (-170, 200), (-170, 100), (-160, 40), (-170, 10), (-150, -10), (-140, 10),
           (-40, -20), (0, -20)],
          [(0, -20), (40, -20), (140, 10), (150, -10), (170, 10), (160, 40), (170, 100), (170, 200), (130, 230), (70, 260),
           (40, 120), (0, 120)]]
ankur2 = [[(-40, -30), (-50, -40), (-100, -46), (-130, -40), (-176, 0), (-186, -30), (-186, -40), (-120, -170), (-110, -210),
           (-80, -230), (-64, -210), (0, -210)],
          [(0, -210), (64, -210), (80, -230), (110, -210), (120, -170), (186, -40), (186, -30), (176, 0), (130, -40),
           (100, -46), (50, -40), (40, -30), (0, -30)]]
ankur3 = [[(-60, -220), (-80, -240), (-110, -220), (-120, -250), (-90, -280), (-60, -260), (-30, -260), (-20, -250),
           (0, -250)],
          [(0, -250), (20, -250), (30, -260), (60, -260), (90, -280), (120, -250), (110, -220), (80, -240), (60, -220),
           (0, -220)]]

turtle.hideturtle()
turtle.bgcolor('#ba161e')  # Dark Red
turtle.setup(500, 600)
turtle.title("I AM IRONMAN")
ankur1Goto = (0, 120)
ankur2Goto = (0, -30)
ankur3Goto = (0, -220)
turtle.speed(2)


def logo(a, b):
    turtle.penup()
    turtle.goto(b)
    turtle.pendown()
    turtle.color('#ffffff')  # Light white
    turtle.begin_fill()

    for i in range(len(a[0])):
        x, y = a[0][i]
        turtle.goto(x, y)

    for i in range(len(a[1])):
        x, y = a[1][i]
        turtle.goto(x, y)
    turtle.end_fill()


logo(ankur1, ankur1Goto)
logo(ankur2, ankur2Goto)
logo(ankur3, ankur3Goto)
turtle.hideturtle()
turtle.done()

flutter fingerprint and face id local authentication implementation

0
flutter fingerprint and face id example
flutter fingerprint and face id auth

In this article, we’ll go over how to use face recognition and Touch ID for biometric authentication in Flutter applications.

To achieve this, we’ll make use of a plugin created by the Flutter team called local auth. The ability to perform local, on-device user authentication is made available by this plugin. With the plugin, we will integrate fingerprint and facial recognition for local authentication in our Flutter applications.

Why is touchID or FaceID authentication necessary?

If you don’t take the necessary steps to protect your information from risk, hackers can easily access the data on your mobile phone. using security measures like Touch ID or Face ID on your phone, or keeping a passcode.

In this flutter tutorial, I’ll show you how to use the flutter local auth plugin to add Touch ID and Face ID authentication capabilities and make a secure flutter application.

In this tutorial, we’ll discuss:

  • Defining biometric authentication
  • How to use the local auth plugin
  • Making a Flutter app use biometric authentication
  • modifying the app’s permissions

What exactly is biometric verification?

Authentication is a technique for conclusively proving that a person is who they claim to be. This verification is carried out using biometric authentication, which examines distinctive biological or behavioral traits.


Set Up the Flutter project to implement local_auth

Step 1: new flutter project creation

$ flutter create app_name

Step 2: For this project, the following plugins are required:

Plugins: Add dependencies to pubspec.yaml file.

Local_auth : ^_._._

Step 3: Import file

import 'package:local_auth/local_auth.dart';

The local auth plugin must then be added to our project as a dependency. To obtain and install the local auth plugin in your project, run the commands below in your terminal.

Step 4: Run flutter packages from your app’s root directory.

$ flutter pub get

Let’s have a look at local auth plugin

Let’s look at the main features offered by the local auth plugin before we continue with the implementation of biometric authentication in our app, which include the following:

Verify the device’s compatibility

Viewable supported biometric types are listed for user authentication using biometrics or PIN.

Two screens will make up our application:

We authenticate users, and the HomeScreen, which users can access following successful authentication.

our LocalAuthenticationService is being set up

In our implementation, we will first determine whether the device supports biometric authentication before restricting the user to only using biometrics as a form of identification. After successful authentication, we will then give the user access to the following screen.
Make a local authentication service.dart file in our service folder and add the following code to it.

final isAvailable = await LocalAuthApi.hasBiometrics();
final biometrics = await LocalAuthApi.getBiometrics();

final hasFingerprint = biometrics.contains(BiometricType.fingerprint);

showDialog(
 context: context,
 builder: (context) => AlertDialog(
   title: const Text('Availability'),
   content: Column(
     crossAxisAlignment: CrossAxisAlignment.start,
     mainAxisSize: MainAxisSize.min,
     children: [
       buildText('Biometrics', isAvailable),
       const Text(
         "Tap on the button to authenticate with the device\'s local authentication system.",
       ),
       buildText('Fingerprint', hasFingerprint),
     ],
   ),
 ),
);
static Future<bool> authenticate() async {
 final isAvailable = await hasBiometrics();
 if (!isAvailable) return false;

 try {
   return await _auth.authenticateWithBiometrics(
     androidAuthStrings: const AndroidAuthMessages(
       signInTitle: "Face ID Required",
     ),
       localizedReason: 'Scan Fingerprint to Authenticate',
       useErrorDialogs: true,
       stickyAuth: false,
       sensitiveTransaction: true);
 } on PlatformException catch (e) {
   return false;
 }
}

Making a Flutter app use biometric authentication

In the code above, we defined the static method authenticateUser and created the class AuthService. The biometric authentication logic is handled by this method, which also returns a bool indicating whether the biometric authentication was successful or not.

As shown in the code snippet below, we now need to call the authenticateUser method in our widget’s onPressed property in the AuthPage.
Make a dart file called AuthPage.dart.

Scaffold(
     appBar: AppBar(
       backgroundColor: Colors.blue.shade900,
       title: const Text("Biometrics authentication app"),
       centerTitle: true,
     ),
     body: Padding(
       padding: const EdgeInsets.all(32),
       child: Center(
         child: Column(
           mainAxisAlignment: MainAxisAlignment.center,
           children: [
             buildAvailability(context),
             const SizedBox(height: 24),
             buildAuthenticate(context),
           ],
         ),
       ),
     ),
   )

If the authentication is successful, the user will be directed to the HomePage from the aforementioned code snippet; otherwise, a Snackbar with an error message is displayed.


Home screen

As shown in the code snippet below, the HomeScreen also includes an Icon and a Button to handle a user logging out.Make a dart file called HomePage.dart

Scaffold(
     appBar: AppBar(
       title: const Text(MyApp.title),
     ),
     body: Padding(
       padding: const EdgeInsets.all(32),
       child: Center(
         child: Column(
           mainAxisAlignment: MainAxisAlignment.center,
           children: [
             const Text(
               'Home',
               style: TextStyle(fontSize: 40),
             ),
             const SizedBox(height: 48),
             buildLogoutButton(context)
           ],
         ),
       ),
     ),
   )

discover the supported biometric types

A list of the biometric types supported by the user’s device can be obtained using the getAvailableBiometrics method offered by the local auth plugin.

static Future<List<BiometricType>> getBiometrics() async {

 try {
   return await _auth.getAvailableBiometrics();
 } on PlatformException catch (e) {
   return <BiometricType>[];
 }
}

The plugin currently supports the following biometric types:

BiometricType.face
BiometricType.fingerprint
BiometricType.iris

Use a PIN or biometrics to verify users

We use the authenticate method offered by the plugin to verify users using biometrics or PIN.

await _auth.authenticateWithBiometrics(
localizedReason : 'Scan Fingerprint to Authenticate',
)

The authenticateWithBiometrics method includes a few optional parameters that can be used to modify a few particular settings. The following are some examples:

return await _auth.authenticateWithBiometrics(
   localizedReason: 'Scan Fingerprint to Authenticate',
   useErrorDialogs: true,
   stickyAuth: false,
   sensitiveTransaction: true);

String localizedReason

The user will be presented with this message when asked to authenticate.

bool biometricOnly

Non-biometric local authentication techniques like PIN and passcode are disabled when set to true.

Note: the “USE PIN” button even when the option is set to false at that time shows the usePin option in your device.

useErrorDialogs: bool

The plugin determines whether a user fingerprint record is stored on the device when this parameter is set to true. The plugin will make an effort to direct the user to the settings so they can register a fingerprint if none already exists.

stickyAuth

Ordinarily, when an app is minimized or put in the background, the authentication process is ended. When the app is brought back into focus, the authentication process is resumed if stickyAuth is set to true.


Adding Fingerprint permission for native platform

For Android app

Add the next line of code to your AndroidManifest.xml file, which is found in the directory android/app/src/main, to include the USE FINGERPRINT permission:

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

Next, replace FlutterActivity with FlutterFragmentActivity in MainActivity.kt file 

import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterFragmentActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine)
    }
}

As an alternative, if you prefer Java to Kotlin, add the following code to your MainActivity.java file:

import android.os.Bundle;
import io.flutter.app.FlutterFragmentActivity;
import io.flutter.plugins.flutter_plugin_android_lifecycle.FlutterAndroidLifecyclePlugin;
import io.flutter.plugins.localauth.LocalAuthPlugin;

public class MainActivity extends FlutterFragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FlutterAndroidLifecyclePlugin.registerWith(
                registrarFor(
                        "io.flutter.plugins.flutter_plugin_android_lifecycle.FlutterAndroidLifecyclePlugin"));
        LocalAuthPlugin.registerWith(registrarFor("io.flutter.plugins.localauth.LocalAuthPlugin"));
    }
}

Conclusion

This tutorial has taught us what biometric authentication is and how to use it in Flutter apps by using the local auth plugin. I hope you enjoyed reading it and that it was useful in helping you create a safe flutter app.In the article, I explained the basic structure of auth ; you can modify this code to suit your needs; and this was a brief introduction to implement authentication in flutter from my end, with Flutter support.

The complete source code of this project is available on GitHub , for source code click here.

https://github.com/Mitali8620/auth_demo.git

draw pokemon pikachu using python

0
Draw Pikachu in Python using Turtle module

In this Python Tutorial, Let’s draw pokemon pikachu using python turtle modle.

pikachu.py

import turtle


def gajurel(x, y):
    turtle.setx(x)
    turtle.sety(y)
    print(x, y)


class Shinchan:

    def __init__(self):
        self.t = turtle.Turtle()
        t = self.t
        t.pensize(3)
        t.speed(9)
        t.ondrag(gajurel)

    def meme(self, x, y):
        self.t.penup()
        self.t.goto(x, y)
        self.t.pendown()

    def aankha1(self, x, y):
        self.meme(x, y)
        t = self.t
        t.seth(0)
        t.fillcolor('#333333')
        t.begin_fill()
        t.circle(22)
        t.end_fill()

        self.meme(x, y + 10)
        t.fillcolor('#000000')
        t.begin_fill()
        t.circle(10)
        t.end_fill()

        self.meme(x + 6, y + 22)
        t.fillcolor('#ffffff')
        t.begin_fill()
        t.circle(10)
        t.end_fill()

    def aankha2(self, x, y):
        self.meme(x, y)
        t = self.t
        t.seth(0)
        t.fillcolor('#333333')
        t.begin_fill()
        t.circle(22)
        t.end_fill()

        self.meme(x, y + 10)
        t.fillcolor('#000000')
        t.begin_fill()
        t.circle(10)
        t.end_fill()

        self.meme(x - 6, y + 22)
        t.fillcolor('#ffffff')
        t.begin_fill()
        t.circle(10)
        t.end_fill()

    def mukh(self, x, y):
        self.meme(x, y)
        t = self.t

        t.fillcolor('#88141D')
        t.begin_fill()
        #
        l1 = []
        l2 = []
        t.seth(190)
        a = 0.7
        for i in range(28):
            a += 0.1
            t.right(3)
            t.fd(a)
            l1.append(t.position())

        self.meme(x, y)

        t.seth(10)
        a = 0.7
        for i in range(28):
            a += 0.1
            t.left(3)
            t.fd(a)
            l2.append(t.position())

        #

        t.seth(10)
        t.circle(50, 15)
        t.left(180)
        t.circle(-50, 15)

        t.circle(-50, 40)
        t.seth(233)
        t.circle(-50, 55)
        t.left(180)
        t.circle(50, 12.1)
        t.end_fill()

        #
        self.meme(17, 54)
        t.fillcolor('#DD716F')
        t.begin_fill()
        t.seth(145)
        t.circle(40, 86)
        t.penup()
        for pos in reversed(l1[:20]):
            t.goto(pos[0], pos[1] + 1.5)
        for pos in l2[:20]:
            t.goto(pos[0], pos[1] + 1.5)
        t.pendown()
        t.end_fill()

        #
        self.meme(-17, 94)
        t.seth(8)
        t.fd(4)
        t.back(8)

    #
    def gaala1(self, x, y):
        turtle.tracer(False)
        t = self.t
        self.meme(x, y)
        t.seth(300)
        t.fillcolor('#DD4D28')
        t.begin_fill()
        a = 2.3
        for i in range(120):
            if 0 <= i < 30 or 60 <= i < 90:
                a -= 0.05
                t.lt(3)
                t.fd(a)
            else:
                a += 0.05
                t.lt(3)
                t.fd(a)
        t.end_fill()
        turtle.tracer(True)

    def gaala2(self, x, y):
        t = self.t
        turtle.tracer(False)
        self.meme(x, y)
        t.seth(60)
        t.fillcolor('#DD4D28')
        t.begin_fill()
        a = 2.3
        for i in range(120):
            if 0 <= i < 30 or 60 <= i < 90:
                a -= 0.05
                t.lt(3)
                t.fd(a)
            else:
                a += 0.05
                t.lt(3)
                t.fd(a)
        t.end_fill()
        turtle.tracer(True)

    def kaan1(self, x, y):
        t = self.t
        self.meme(x, y)
        t.fillcolor('#000000')
        t.begin_fill()
        t.seth(330)
        t.circle(100, 35)
        t.seth(219)
        t.circle(-300, 19)
        t.seth(110)
        t.circle(-30, 50)
        t.circle(-300, 10)
        t.end_fill()

    def kaan2(self, x, y):
        t = self.t
        self.meme(x, y)
        t.fillcolor('#000000')
        t.begin_fill()
        t.seth(300)
        t.circle(-100, 30)
        t.seth(35)
        t.circle(300, 15)
        t.circle(30, 50)
        t.seth(190)
        t.circle(300, 17)
        t.end_fill()

    def jiu(self):
        t = self.t

        t.fillcolor('#F6D02F')
        t.begin_fill()
        #
        t.penup()
        t.circle(130, 40)
        t.pendown()
        t.circle(100, 105)
        t.left(180)
        t.circle(-100, 5)

        #
        t.seth(20)
        t.circle(300, 30)
        t.circle(30, 50)
        t.seth(190)
        t.circle(300, 36)

        #
        t.seth(150)
        t.circle(150, 70)

        #
        t.seth(200)
        t.circle(300, 40)
        t.circle(30, 50)
        t.seth(20)
        t.circle(300, 35)
        # print(t.pos())

        #
        t.seth(240)
        t.circle(105, 95)
        t.left(180)
        t.circle(-105, 5)

        #
        t.seth(210)
        t.circle(500, 18)
        t.seth(200)
        t.fd(10)
        t.seth(280)
        t.fd(7)
        t.seth(210)
        t.fd(10)
        t.seth(300)
        t.circle(10, 80)
        t.seth(220)
        t.fd(10)
        t.seth(300)
        t.circle(10, 80)
        t.seth(240)
        t.fd(12)
        t.seth(0)
        t.fd(13)
        t.seth(240)
        t.circle(10, 70)
        t.seth(10)
        t.circle(10, 70)
        t.seth(10)
        t.circle(300, 18)

        t.seth(75)
        t.circle(500, 8)
        t.left(180)
        t.circle(-500, 15)
        t.seth(250)
        t.circle(100, 65)

        #
        t.seth(320)
        t.circle(100, 5)
        t.left(180)
        t.circle(-100, 5)
        t.seth(220)
        t.circle(200, 20)
        t.circle(20, 70)

        t.seth(60)
        t.circle(-100, 20)
        t.left(180)
        t.circle(100, 20)
        t.seth(300)
        t.circle(10, 70)

        t.seth(60)
        t.circle(-100, 20)
        t.left(180)
        t.circle(100, 20)
        t.seth(10)
        t.circle(100, 60)

        #
        t.seth(180)
        t.circle(-100, 10)
        t.left(180)
        t.circle(100, 10)
        t.seth(5)
        t.circle(100, 10)
        t.circle(-100, 40)
        t.circle(100, 35)
        t.left(180)
        t.circle(-100, 10)

        #
        t.seth(290)
        t.circle(100, 55)
        t.circle(10, 50)

        t.seth(120)
        t.circle(100, 20)
        t.left(180)
        t.circle(-100, 20)

        t.seth(0)
        t.circle(10, 50)

        t.seth(110)
        t.circle(100, 20)
        t.left(180)
        t.circle(-100, 20)

        t.seth(30)
        t.circle(20, 50)

        t.seth(100)
        t.circle(100, 40)

        #
        t.seth(200)
        t.circle(-100, 5)
        t.left(180)
        t.circle(100, 5)
        t.left(30)
        t.circle(100, 75)
        t.right(15)
        t.circle(-300, 21)
        t.left(180)
        t.circle(300, 3)

        #
        t.seth(43)
        t.circle(200, 60)

        t.right(10)
        t.fd(10)

        t.circle(5, 160)
        t.seth(90)
        t.circle(5, 160)
        t.seth(90)

        t.fd(10)
        t.seth(90)
        t.circle(5, 180)
        t.fd(10)

        t.left(180)
        t.left(20)
        t.fd(10)
        t.circle(5, 170)
        t.fd(10)
        t.seth(240)
        t.circle(50, 30)

        t.end_fill()
        self.meme(130, 125)
        t.seth(-20)
        t.fd(5)
        t.circle(-5, 160)
        t.fd(5)

        #
        self.meme(166, 130)
        t.seth(-90)
        t.fd(3)
        t.circle(-4, 180)
        t.fd(3)
        t.seth(-90)
        t.fd(3)
        t.circle(-4, 180)
        t.fd(3)

        #
        self.meme(168, 134)
        t.fillcolor('#F6D02F')
        t.begin_fill()
        t.seth(40)
        t.fd(200)
        t.seth(-80)
        t.fd(150)
        t.seth(210)
        t.fd(150)
        t.left(90)
        t.fd(100)
        t.right(95)
        t.fd(100)
        t.left(110)
        t.fd(70)
        t.right(110)
        t.fd(80)
        t.left(110)
        t.fd(30)
        t.right(110)
        t.fd(32)

        t.right(106)
        t.circle(100, 25)
        t.right(15)
        t.circle(-300, 2)
        ##############
        # print(t.pos())
        t.seth(30)
        t.fd(40)
        t.left(100)
        t.fd(70)
        t.right(100)
        t.fd(80)
        t.left(100)
        t.fd(46)
        t.seth(66)
        t.circle(200, 38)
        t.right(10)
        t.fd(10)
        t.end_fill()

        #
        t.fillcolor('#923E24')
        self.meme(126.82, -156.84)
        t.begin_fill()

        t.seth(30)
        t.fd(40)
        t.left(100)
        t.fd(40)
        t.pencolor('#923e24')
        t.seth(-30)
        t.fd(30)
        t.left(140)
        t.fd(20)
        t.right(150)
        t.fd(20)
        t.left(150)
        t.fd(20)
        t.right(150)
        t.fd(20)
        t.left(130)
        t.fd(18)
        t.pencolor('#000000')
        t.seth(-45)
        t.fd(67)
        t.right(110)
        t.fd(80)
        t.left(110)
        t.fd(30)
        t.right(110)
        t.fd(32)
        t.right(106)
        t.circle(100, 25)
        t.right(15)
        t.circle(-300, 2)
        t.end_fill()

        self.topi(-134.07, 147.81)
        self.mukh(-5, 25)
        self.gaala1(-126, 32)
        self.gaala2(107, 63)
        self.kaan1(-250, 100)
        self.kaan2(140, 270)
        self.aankha1(-85, 90)
        self.aankha2(50, 110)
        t.hideturtle()

    def topi(self, x, y):
        self.meme(x, y)
        t = self.t
        t.fillcolor('#CD0000')
        t.begin_fill()
        t.seth(200)
        t.circle(400, 7)
        t.left(180)
        t.circle(-400, 30)
        t.circle(30, 60)
        t.fd(50)
        t.circle(30, 45)
        t.fd(60)
        t.left(5)
        t.circle(30, 70)
        t.right(20)
        t.circle(200, 70)
        t.circle(30, 60)
        t.fd(70)
        # print(t.pos())
        t.right(35)
        t.fd(50)
        t.circle(8, 100)
        t.end_fill()
        self.meme(-168.47, 185.52)
        t.seth(36)
        t.circle(-270, 54)
        t.left(180)
        t.circle(270, 27)
        t.circle(-80, 98)

        t.fillcolor('#444444')
        t.begin_fill()
        t.left(180)
        t.circle(80, 197)
        t.left(58)
        t.circle(200, 45)
        t.end_fill()

        self.meme(-58, 270)
        t.pencolor('#228B22')
        t.dot(35)

        self.meme(-30, 280)
        t.fillcolor('#228B22')
        t.begin_fill()
        t.seth(100)
        t.circle(30, 180)
        t.seth(190)
        t.fd(15)
        t.seth(100)
        t.circle(-45, 180)
        t.right(90)
        t.fd(15)
        t.end_fill()
        t.pencolor('#000000')

    def start(self):
        self.jiu()


def main():
    print('Painting the Cartoon... ')
    turtle.screensize(800, 600)
    turtle.title('Cartoon')
    cartoon = Shinchan()
    cartoon.start()
    turtle.mainloop()


if __name__ == '__main__':
    main()