Provides the ability to lock the screen on ios and android. Biometric authentication can be used in addition to passcode.

Overview

Flutter Screen Lock

This Flutter plugin provides an feature for screen lock. Enter your passcode to unlock the screen. You can also use biometric authentication as an option.

4.x to 5 migration

Change to the next import only.

import 'package:flutter_screen_lock/flutter_screen_lock.dart';

Features

  • By the length of the character count
  • You can change Cancel and Delete widget
  • Optimizes the UI for device size and orientation
  • You can disable cancellation
  • You can use biometrics (local_auth plugin)
  • Biometrics can be displayed on first launch
  • Unlocked callback
  • You can specify a mismatch event.
  • Limit the maximum number of retries

Usage

You can easily lock the screen with the following code.
To unlock, enter correctString.

Simple

If you give the same input as correctString, it will automatically close the screen.

import 'package:flutter_screen_lock/flutter_screen_lock.dart';

screenLock(
  context: context,
  correctString: '1234',
);

Change digits

Provides a screen lock that cannot be canceled.

import 'package:flutter_screen_lock/flutter_screen_lock.dart';

screenLock(
  context: context,
  correctString: '1234',
  canCancel: false,
);

Confirmation screen

You can display the confirmation screen and get the first input with didConfirmed if the first and second inputs match.

import 'package:flutter_screen_lock/flutter_screen_lock.dart';

screenLock(
  context: context,
  correctString: '',
  confirmation: true,
  didConfirmed: (matchedText) {
    print(matchedText);
  },
);

Control the confirmation state

import 'package:flutter_screen_lock/flutter_screen_lock.dart';

final inputController = InputController();

screenLock(
  context: context,
  correctString: '',
  confirmation: true,
  inputController: inputController,
);

// Release the confirmation state at any event.
inputController.unsetConfirmed();

Use local_auth

Add the local_auth package to pubspec.yml.

https://pub.dev/packages/local_auth

It includes an example that calls biometrics as soon as screenLock is displayed in didOpened.

import 'package:flutter_screen_lock/flutter_screen_lock.dart';
import 'package:local_auth/local_auth.dart';
import 'package:flutter/material.dart';

/// Method extraction to call by initial display and custom buttons.
Future<void> localAuth(BuildContext context) async {
  final localAuth = LocalAuthentication();
  final didAuthenticate = await localAuth.authenticateWithBiometrics(
      localizedReason: 'Please authenticate');
  if (didAuthenticate) {
    Navigator.pop(context);
  }
}

screenLock(
  context: context,
  correctString: '1234',
  customizedButtonChild: Icon(
    Icons.fingerprint,
  ),
  customizedButtonTap: () async {
    await localAuth(context);
  },
  didOpened: () async {
    await localAuth(context);
  },
);

Full customize

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

screenLock(
  context: context,
  title: Text('change title'),
  confirmTitle: Text('change confirm title'),
  correctString: '1234',
  confirmation: true,
  screenLockConfig: ScreenLockConfig(
    backgroundColor: Colors.deepOrange,
  ),
  secretsConfig: SecretsConfig(
    spacing: 15, // or spacingRatio
    padding: const EdgeInsets.all(40),
    secretConfig: SecretConfig(
      borderColor: Colors.amber,
      borderSize: 2.0,
      disabledColor: Colors.black,
      enabledColor: Colors.amber,
      height: 15,
      width: 15,
      build: (context, {config, enabled}) {
        return SizedBox(
          child: Container(
            decoration: BoxDecoration(
              shape: BoxShape.rectangle,
              color: enabled
                  ? config.enabledColor
                  : config.disabledColor,
              border: Border.all(
                width: config.borderSize,
                color: config.borderColor,
              ),
            ),
            padding: EdgeInsets.all(10),
            width: config.width,
            height: config.height,
          ),
          width: config.width,
          height: config.height,
        );
      },
    ),
  ),
  inputButtonConfig: InputButtonConfig(
    textStyle:
        InputButtonConfig.getDefaultTextStyle(context).copyWith(
      color: Colors.orange,
      fontWeight: FontWeight.bold,
    ),
    buttonStyle: OutlinedButton.styleFrom(
      shape: RoundedRectangleBorder(),
      backgroundColor: Colors.deepOrange,
    ),
  ),
  cancelButton: const Icon(Icons.close),
  deleteButton: const Icon(Icons.delete),
);


API References

screenLock / ScreenLock API

Property Type Default Description
context BuildContext (Required) [screenLock] only
correctString String (Required) Input correct String
If [confirmation] is true, it will be ignored, so set it to any string or empty.
screenLockConfig ScreenLockConfig ScreenLockConfig() Refer to the API of ScreenLockConfig
secretsConfig SecretsConfig SecretsConfig() Refer to the API of SecretsConfig
inputButtonConfig InputButtonConfig InputButtonConfig() Refer to the API of InputButtonConfig
canCancel bool true true is show cancel button. (Default: true)
confirmation bool Make sure the first and second inputs are the same.
digits int Set the maximum number of characters to enter when [confirmation] is true.
maxRetries int 0 0 is unlimited.
For example, if it is set to 1, didMaxRetries will be called on the first failure.
didUnlocked void Function() Called if the value matches the correctString.
didError void Function(int retries) Called if the value does not match the correctString.
didMaxRetries void Function(int retries) Events that have reached the maximum number of attempts.
didOpened void Function() For example, when you want to perform biometric authentication. [screenLock] only
didConfirmed void Function(String matchedText) Called when the first and second inputs match during confirmation.
It is possible to receive the matched text as an argument.
customizedButtonTap Future<void> Function() Tapped for left side lower button.
customizedButtonChild Widget Child for bottom left side button.
footer Widget Add a Widget to the footer.
cancelButton Widget Change the child widget for the cancel button.
deleteButton Widget Change the child widget for the delete button.
title Widget HeadingTitle(text: 'Please enter passcode.') Change the title widget.
confirmTitle Widget HeadingTitle(text: 'Please enter confirm passcode.') Change the confirm title widget.
inputController InputController Control the confirmation state change on the outside.
withBlur bool Blur the background

ScreenLockConfig API

Property Type Default Description
backgroundColor Color Specifies the background color of the screen. By default, themeData will be set.
themeData ThemeData ScreenLockConfig.defaultThemeData

SecretsConfig API

Property Type Default Description
spacing double Absolute space between secret widgets.
If specified together with spacingRatio, this will take precedence.
spacingRatio double 0.05 Space ratio between secret widgets.
padding EdgeInsetsGeometry EdgeInsets.only(top: 20, bottom: 50) padding of Secrets Widget.
secretConfig SecretConfig SecretConfig() Refer to the API of SecretConfig

SecretConfig API

Property Type Default Description
width double 16 Widget width.
height double 16 Widget height.
borderSize double 1.0 border size.
borderColor Color Color(0xFFFFFFFF) border color.
enabledColor Color Color(0xFFFFFFFF) Fill color when input is active.
disabledColor Color Color(0xFFFFFFFF) Fill color for unentered.

InputButtonConfig API

Property Type Default Description
height double MediaQuery.of(context).size.height * 0.6 * 0.16 Button height.
width double MediaQuery.of(context).size.width * 0.22 Button width.
autoSize bool true Automatically adjust the size of the square to fit the orientation of the device.
inputStrings List<String> ['0','1','2','3','4','5','6','7','8','9'] A string to be matched against correctString.
displayStrings List<String> ['0','1','2','3','4','5','6','7','8','9'] The string to be displayed on the screen.
style ButtonStyle It is recommended that you use [OutlinedButton.styleFrom()] to change it.
textStyle TextStyle Changes the text style of the button.

Apps I use

TimeKey

iOS

Android

Back me up!

Buy Me A Coffee

Comments
  • "Reset" button needed

    First of all, thank you for this awesome package! This is a feature request.

    In case when I`m setting pin code first time and miss clicked then I can not enter the same code one more time. It is not a problem if I trying to change old pin code. But if setting of pin code is mandatory on first run, I should unload app to make a new try. It is not clear for many users. So, I need to write much code to make it work my way. I guess, not only mine.

    Thank you!

    enhancement 
    opened by alexandrim0 8
  • How to go back on first screen(first input controller from confirm password controller)

    How to go back on first screen(first input controller from confirm password controller)

    If user on confirmation screen and he presss back button then how to navigate to previous screen means first password screen. Suppose a user on the first screen where he enter a password after that he navigates to confirm password screen so how user go back from confirm password screen to set password screen. please help

    enhancement 
    opened by ghost 8
  • Fingerprint not working!

    Fingerprint not working!

    checkPassword() async{
        SharedPreferences _preferences = await SharedPreferences.getInstance();
        _password = _preferences.getString(_key);
        _isFingerprintEnabled = _preferences.getBool(_fingerprintKey);
        showLockScreen(
          context: context,
          title: "Enter vault password",
          digits: 5,
          correctString: _password,
          cancelText: "Close",
          showBiometricFirst: true,
          canCancel: false,
          onUnlocked: () => Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => Home())),
          canBiometric: _isFingerprintEnabled,
          biometricAuthenticate: (context) async {
            final localAuth = LocalAuthentication();
            final didAuthenticate = await localAuth.authenticateWithBiometrics(
                localizedReason: 'Please authenticate');
    
            if (didAuthenticate) {
              return true;
            }
    
            return false;
          },
        );
      }
    

    This is my code but fingerprint not working means after clicking on Fingerprint icon nothing is happening.

    opened by jaydip-pawar 8
  • Fix various Theme issues

    Fix various Theme issues

    • Fixed ScreenLockConfig Title styling from ThemeData
    • Added KeyPadButtonConfig for Actions and assigned reasonable default
    • Renamed config parameters
    • Corrected some documentation typos
    • Fix #91

    The way I changed ScreenLockConfig in the last update showed that there is an issue with this:

    ScreenLockConfig(
      theme: ThemeData.of(context),
    )
    

    The user would get a very large title because it was using headline1. I changed it to headline6 (appbar size) which is more reasonable. The above usage is intended, so it is expected to have a sane standard.

    I also changed the hardcoded font size for the cancel button, which is now configurable in the KeyPadConfig as actionButtonConfig. This also influences the delete and fingerprint button.

    I also renamed the screenLockConfig parameter to just config, as it is clear what we are configuring.

    opened by clragon 6
  • Replace HeadingText with DefaultTextTheme

    Replace HeadingText with DefaultTextTheme

    Currently, we are using HeadingText to apply the right style to our Text when they are displayed above the Secrets. This also means we have to export HeadingText for users to specify their own Text with the same style. That is inconvenient.

    Instead we can do what AppBar does for its title property. We let the user provide a normal Text and then wrap it in a DefaultTextTheme which applies our text style. If the user wants to opt out of that, they just have to provide a text style to their Text widget.

    I will make a merge request for this, once other things are merged, so that there will be no conflicts.

    opened by clragon 6
  • The password input panel responses slowly when input.

    The password input panel responses slowly when input.

    When I type quickly on the password input panel, it can not response timely. For example, I typed four number quickly, but only two were inputed, there were two types not being corresponded. And when user inputs a familiar password, it's common to input quickly. I suspect that Flutter set a least interval between gesture actions, but I can't find related doc or code. Do you have any idea about that?

    opened by cyx114 6
  • Add some extra functionality!

    Add some extra functionality!

    I want some extra features, like many app which uses lock screen contains options like lock app after 30 sec or 1 min when user doesn't interact with and after screen lock after particular time lock the app, so can we add this features in our package?

    opened by jaydip-pawar 5
  • Can I show this Lock screen at Bottom of Application?

    Can I show this Lock screen at Bottom of Application?

    First of all, thank you for this awesome library. But i want to know that can i change the alignment of this screen? like when we show this screen it starts from top of the screen so on the end much more space remaining empty. So, my question is that how to start the screen from bottom of my application so if any space remain it remains at top not at bottom.

    opened by jaydip-pawar 5
  • Support Delaying when max retries was exceeded

    Support Delaying when max retries was exceeded

    It's a very popular scenario when max retries is exceeded and user should be waiting, for example: 5min, before next retry. didMaxRetries is quite complex to handle that scenario. it's will be great if you can support that scenario out of the box, I appreciate that.

    opened by bigbang489 4
  • Replaced HeadingTitle with DefaultTextStyle

    Replaced HeadingTitle with DefaultTextStyle

    fix #75

    merge request #76 but without a breaking oversight.

    cannot be merged into fix/delay-screen because of conflicts by the revert.

    (sorry, I forgot a tiny change on a line and it caused the issue!)

    opened by clragon 3
  • Unhandled Exception: A ValueNotifier<String> was used after being disposed

    Unhandled Exception: A ValueNotifier was used after being disposed

    Hi I'm observing the following issue with Android. As far as I remember there were no issue before. This seems related to a bug you fixed recently. I observe this on Android emulators 8.1 and 11.

    I tried your versions 5.0.9 and 5.0.10, both have same issues. This happens when the Lock Screen is dismissed after the code was entered.

    Any idea about this ? Thanks

    E/flutter ( 6937): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: A ValueNotifier<String> was used after being disposed.
    E/flutter ( 6937): Once you have called dispose() on a ValueNotifier<String>, it can no longer be used.
    E/flutter ( 6937): #0      ChangeNotifier._debugAssertNotDisposed.<anonymous closure> (package:flutter/src/foundation/change_notifier.dart:114:9)
    E/flutter ( 6937): #1      ChangeNotifier._debugAssertNotDisposed (package:flutter/src/foundation/change_notifier.dart:120:6)
    E/flutter ( 6937): #2      ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:288:12)
    E/flutter ( 6937): #3      ValueNotifier.value= (package:flutter/src/foundation/change_notifier.dart:412:5)
    E/flutter ( 6937): #4      InputController.dispose (package:flutter_screen_lock/src/input_controller.dart:119:25)
    E/flutter ( 6937): #5      _ScreenLockState.dispose.<anonymous closure> (package:flutter_screen_lock/src/screen_lock.dart:240:29)
    E/flutter ( 6937): #6      new Future.microtask.<anonymous closure> (dart:async/future.dart:276:37)
    E/flutter ( 6937): #7      _rootRun (dart:async/zone.dart:1418:47)
    E/flutter ( 6937): #8      _CustomZone.run (dart:async/zone.dart:1328:19)
    E/flutter ( 6937): #9      _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
    E/flutter ( 6937): #10     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
    E/flutter ( 6937): #11     _rootRun (dart:async/zone.dart:1426:13)
    E/flutter ( 6937): #12     _CustomZone.run (dart:async/zone.dart:1328:19)
    E/flutter ( 6937): #13     _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
    E/flutter ( 6937): #14     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
    E/flutter ( 6937): #15     _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
    E/flutter ( 6937): #16     _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
    
    opened by jeromeDms 3
  • Customize the keyPadConfig of the confirm screen.

    Customize the keyPadConfig of the confirm screen.

    I am using your package well. Thank you.

    In confirmation:true I want to be able to customize the keyPadConfig of the confirmation screen. I would like to have different keypads for the two screens of confirmation:true.

    Thank you.

    opened by ttb-inc 1
  • physical keyboard input support

    physical keyboard input support

    It would be great if the package supported input via a physical keyboard.

    I have already tested a rough implementation of this:

    final FocusNode _focusNode = FocusNode();
    
    bool _canInput = true;
    
    void _blockInput() {
      _canInput = false;
      Timer(const Duration(milliseconds: 100), () => _canInput = true);
    }
    
    @override
    void initState() {
      super.initState();
      _focusNode.requestFocus();
    }
    
    @override
    void didChangeDependencies() {
      super.didChangeDependencies();
      FocusScope.of(context).autofocus(_focusNode);
    }
    
    @override
    void dispose() {
      _focusNode.dispose();
      super.dispose();
    }
    
    @override
    Widget build(BuildContext context) {
      return KeyboardListener(
        focusNode: _focusNode,
        onKeyEvent: (key) {
          if (!_canInput) {
            return;
          }
          if (widget.inputButtonConfig.inputStrings.contains(key.character)) {
            widget.inputState.addCharacter(key.character!);
            _blockInput();
          }
          if (key.logicalKey == LogicalKeyboardKey.backspace) {
            widget.inputState.removeCharacter();
            _blockInput();
          }
        },
        child: widget.child,
      );
    }
    

    It can be used as a widget wrapped around a keypad to enter a PIN code from the keyboard. There are some issues with delays. KeyEvent can be triggered very fast. Maybe only add delay on backspace? not sure.

    I probably won't make a pull request. I don't want to change the structure of your project too much. But I think this feature is a great addition.

    opened by clragon 4
Releases(v9.0.0)
Owner
Naoki
I like Flutter and Dart
Naoki
Android test task master - Create PIN code screen, authentication by PIN code screen and menu screen

Here is described test tasks for a android dev. Need to implement three screens:

null 3 Oct 4, 2022
Flutter plugin that secures your secrets in keychain using biometric authentication (Fingerprint, Touch ID, Face ID...).

Flutter Locker ?? Flutter plugin that secures your secrets in keychain using biometric authentication (Fingerprint, Touch ID, Face ID...). It uses: Lo

Infinum 25 Nov 21, 2022
Flutterbiometric - A sample app showing how to implement biometric authentication in flutter

Flutter Tutorial - Fingerprint & Touch ID - Local Auth By using Flutter Local Au

null 0 Jan 1, 2022
This is an auction application just like eBay. Using firebase as the backend for signup & sign-in functionality. In addition to that, it's a two pages application with user bid in input and count down view.

Nilam This is an auction application just like eBay. Using firebase as the backend for signup & sign-in functionality. In addition to that, it's a two

Md. Siam 5 Nov 9, 2022
This package gives you lock screen or pass code page

Flutter Pass Code Page or Pin Code Page Package This package gives you beautiful pass code page for using both android and ios. Demo Finger Print Usag

Yasin ilhan 61 Aug 22, 2022
A dart timer that can be configured to fire once or repeatedly with ability start, stop, resume and cancel.

A timer that can be configured to fire once or repeatedly with ability start, stop, resume and cancel. Getting started Add CompleteTimer to your pubsp

MohammadAminZamani.afshar 3 Jul 20, 2022
Backs up Android devices on Linux, macOS and Windows. Backup your device without vendor lock-ins, using insecure software or root.

Backs up Android devices on Linux, macOS and Windows. Backup your device without vendor lock-ins, using insecure software or root. Supports encryption and compression out of the box.

null 255 Dec 31, 2022
Doctor Consultation App in Flutter containing splash screen on boarding screen Routing state management Dash board Bottom navigation Decorated Drawer and Doctors Screen in the last.

Online doctor Consultation App UI in Flutter Doctor Consultation App UI in Flutter Visit Website Features State Management Navigation Bar Responsive D

Habib ullah 14 Jan 1, 2023
User auth form - Signup and signin user auth form with ability to stay signed in and have an option to signout.

user_auth_form SIgnup and signin user authentification form Getting Started This project is a starting point for a Flutter application. A few resource

null 0 Jan 6, 2022
A basic login/register screen that can be used as a template for future Flutter projects.

A Flutter / Firebase login screen A simple flutter/dart based login-screen that connects with Firebase Auth to enable users to sign-in/up with Email o

Kim Andre Langholz 142 Dec 20, 2022
A Flutter plugin that provides assets abstraction management APIs without UI integration, you can get assets (image/video/audio) on Android, iOS and macOS.

photo_manager Photo/Assets management APIs for Flutter without UI integration, you can get assets (image/video/audio) from Android, iOS and macOS. 提供相

FlutterCandies 526 Jan 4, 2023
Rotate Dial Lock

Rotary dial Locker Dependencies : How it works Most magic handle by GuesterDetector. onPanEnd onPanDown onPanUpdate SpringHouse, 1st we locate where u

Md. Yeasin Sheikh 10 Dec 21, 2022
Socket library for creating real-time multiplayer games. Based on TCP, with the ability to send messages over UDP (planned).

Game socket The library was published in early access and is not stable, as it is being developed in parallel with other solutions. English is not a n

Stanislav 10 Aug 10, 2022
A powerful plugin that fully uses the native image library's ability to display images on the flutter side.

PowerImage A powerful plugin that fully uses the native image library's ability to display images on the flutter side. 中文文档 Features: Supports the abi

Alibaba 422 Dec 23, 2022
This package give you ability to integrate with Drone API easily in any platform using Dart

Drone Dart Dart is a multi client programming language which allow you to compile and run your code on multiple platforms. Because of that we decided

Amirhossein 1 Dec 22, 2022
Rolify is an app that allows you to play multiple sounds simultaneously, with the ability to manage audio individually

Rolify is an app that allows you to play multiple sounds simultaneously, with the ability to manage audio individually. You can also add the music you have on your phone, all completely offline and free.

Luca Oropallo 4 Sep 30, 2022
Authentication + Splash Screen Flutter UI, UI created getting inspired from one share on dribble with flutter

Rest App, with Firebase Auth + SplashScreen UI created getting inspired from one share on dribble with flutter, after getting amazing responce, Added

Sanskar Tiwari 202 Dec 17, 2022