A highly customizable Flutter package for face liveness detection with multiple challenge types. This package helps you verify that a real person is present in front of the camera, not a photo, video, or mask.
- π― Multiple liveness challenge types (blinking, smiling, head turns, nodding, zoom, center the face, tilt up, tilt down)
- π Random challenge sequence generation for enhanced security
- π― Face centering guidance with visual feedback
- π Anti-spoofing measures (screen glare detection, motion correlation)
- π¨ Fully customizable UI with theming support
- π Animated progress indicators, status displays, and overlays
- π¬ Challenge hint animations with GIF/Lottie support
- π± Simple integration with Flutter apps
- πΈ Optional image capture capability
Add this package to your pubspec.yaml:
dependencies:
smart_liveliness_detection: ^0.2.3Then run:
flutter pub get
Make sure to add camera permissions to your app:
Add the following to your Info.plist:
<key>NSCameraUsageDescription</key>
<string>This app needs camera access for face liveness verification</string>Add the following to your AndroidManifest.xml:
<uses-permission android:name="android.permission.CAMERA" />Here's how to quickly integrate face liveness detection into your app:
import 'package:camera/camera.dart';
import 'package:smart_liveliness_detection/smart_liveliness_detection.dart';
import 'package:flutter/material.dart';
import 'package:flutter/developer.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Get available cameras
final cameras = await availableCameras();
runApp(MyApp(cameras: cameras));
}
class MyApp extends StatelessWidget {
final List<CameraDescription> cameras;
const MyApp({Key? key, required this.cameras}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Liveness Detection')),
body: LivenessDetectionScreen(
cameras: cameras,
onLivenessCompleted: (sessionId, isSuccessful, metadata) {
log('Liveness verification completed: $isSuccessful');
log('Session ID: $sessionId');
if (metadata != null) {
log('Anti-spoofing check results: ${metadata['antiSpoofingDetection']}');
}
},
),
),
);
}
}Customize the detection settings using LivenessConfig:
LivenessConfig config = LivenessConfig(
// Challenge configuration
challengeTypes: [ChallengeType.blink, ChallengeType.smile, ChallengeType.turnRight],
numberOfRandomChallenges: 3,
alwaysIncludeBlink: true,
// Custom instructions
challengeInstructions: {
ChallengeType.blink: 'Please blink your eyes now',
ChallengeType.smile: 'Show us your best smile',
},
// Detection thresholds
eyeBlinkThresholdOpen: 0.7,
eyeBlinkThresholdClosed: 0.3,
smileThresholdNeutral: 0.3,
smileThresholdSmiling: 0.7,
headTurnThreshold: 20.0,
// UI configuration
ovalHeightRatio: 0.9,
ovalWidthRatio: 0.9,
strokeWidth: 4.0,
// Session settings
maxSessionDuration: Duration(minutes: 2),
);LivenessDetectionScreen(
config: LivenessConfig(
// ... other settings
messages: const LivenessMessages(
// Face Centering Messages
moveFartherAway: 'Afaste-se um pouco',
moveCloser: 'Aproxime-se',
moveLeft: 'Mova para a esquerda',
moveRight: 'Mova para a direita',
moveUp: 'Mova para cima',
moveDown: 'Mova para baixo',
perfectHoldStill: 'Perfeito! Fique parado',
noFaceDetected: 'Nenhum rosto detectado',
// Process Status Messages
initializing: 'Inicializando...',
initialInstruction: 'Posicione seu rosto no oval',
poorLighting: 'Por favor, vΓ‘ para uma Γ‘rea mais iluminada',
processingVerification: 'Processando verificaΓ§Γ£o...',
verificationComplete: 'VerificaΓ§Γ£o concluΓda!',
errorInitializingCamera: 'Erro ao iniciar a cΓ’mera. Por favor, reinicie.',
spoofingDetected: 'PossΓvel fraude detectada',
),
),
onLivenessCompleted: (sessionId, isSuccessful, data) {
// ...
},
)
Customize the appearance using LivenessTheme:
LivenessTheme theme = LivenessTheme(
// Colors
primaryColor: Colors.blue,
successColor: Colors.green,
errorColor: Colors.red,
warningColor: Colors.orange,
ovalGuideColor: Colors.purple,
// Text styles
instructionTextStyle: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
guidanceTextStyle: TextStyle(
color: Colors.blue,
fontSize: 16,
),
// Progress indicator
progressIndicatorColor: Colors.blue,
progressIndicatorHeight: 12,
// Animation
useOvalPulseAnimation: true,
);Or use a theme based on Material Design:
LivenessTheme theme = LivenessTheme.fromMaterialColor(
Colors.teal,
brightness: Brightness.dark,
);Display animated GIF or Lottie hints to guide users through challenges:
Enable built-in hint animations with default settings:
LivenessDetectionScreen(
cameras: cameras,
config: LivenessConfig(
defaultChallengeHintConfig: ChallengeHintConfig(
enabled: true,
position: ChallengeHintPosition.topCenter,
size: 100.0,
displayDuration: Duration(seconds: 2),
),
),
);Configure different hints for specific challenge types:
LivenessDetectionScreen(
cameras: cameras,
config: LivenessConfig(
challengeHints: {
ChallengeType.blink: ChallengeHintConfig(
enabled: true,
position: ChallengeHintPosition.topCenter,
size: 120.0,
),
ChallengeType.smile: ChallengeHintConfig(
enabled: true,
position: ChallengeHintPosition.bottomCenter,
size: 100.0,
),
ChallengeType.turnLeft: ChallengeHintConfig(
enabled: false, // Disable hint for this challenge
),
},
// Fallback for challenges not in the map
defaultChallengeHintConfig: ChallengeHintConfig(
enabled: true,
),
),
);Use your own animations:
// Custom GIF
ChallengeHintConfig(
enabled: true,
assetPath: 'assets/my_animations/custom_blink.gif',
position: ChallengeHintPosition.topCenter,
size: 100.0,
)
// Custom Lottie (requires lottie package)
ChallengeHintConfig(
enabled: true,
assetPath: 'assets/my_animations/custom_smile.json',
isLottie: true,
position: ChallengeHintPosition.bottomCenter,
)Available Positions:
ChallengeHintPosition.topCenterChallengeHintPosition.bottomCenterChallengeHintPosition.topLeftChallengeHintPosition.topRightChallengeHintPosition.bottomLeftChallengeHintPosition.bottomRight
Built-in Hint Animations:
The package includes default GIF animations for:
ChallengeType.blink- Eye blinking animationChallengeType.smile- Smiling animationChallengeType.nod- Head nodding animationChallengeType.turnLeft- Head rotating left animationChallengeType.turnRight- Head rotating right animation
For a complete guide on challenge hints, see CHALLENGE_HINTS.md.
Get notified about challenges and session completion:
LivenessDetectionScreen(
cameras: cameras,
config: config,
theme: theme,
onChallengeCompleted: (challengeType) {
log('Challenge completed: $challengeType');
},
onLivenessCompleted: (sessionId, isSuccessful, metadata) {
log('Liveness verification completed:');
log('Session ID: $sessionId');
log('Overall Success: $isSuccessful');
if (metadata != null && metadata.containsKey('antiSpoofingDetection')) {
final antiSpoofingResult = metadata['antiSpoofingDetection'];
final didPassMotionCheck = !antiSpoofingResult['motionCorrelationCheckFailed'];
final didPassGlareCheck = !antiSpoofingResult['screenGlareDetected'];
final didPassContourCheck = !antiSpoofingResult['lackOfFacialContoursDetected'];
log('Motion Check Passed: $didPassMotionCheck');
log('Glare Check Passed: $didPassGlareCheck');
log('Contour Check Passed: $didPassContourCheck');
}
// You can now send this session ID and the detailed results to your backend
// for verification or proceed with your app flow.
},
);Customize the UI with your own components:
LivenessDetectionScreen(
cameras: cameras,
showAppBar: false, // Hide default app bar
customAppBar: AppBar(
title: const Text('My Custom Verification'),
backgroundColor: Colors.transparent,
),
customSuccessOverlay: MyCustomSuccessWidget(),
);Enable capturing the user's image after successful verification:
LivenessDetectionScreen(
cameras: cameras,
captureFinalImage: true, // Enable final image capture
onFinalImageCaptured: (sessionId, imageFile, metadata) {
// imageFile is an XFile that contains the captured image
log('Image saved to: ${imageFile.path}');
// The metadata map contains the detailed anti-spoofing results
final antiSpoofingResult = metadata['antiSpoofingDetection'];
log('Anti-spoofing results from capture: $antiSpoofingResult');
// You can now:
// 1. Display the image
// 2. Upload it to your server along with the metadata
// 3. Store it locally
},
);You can incorporate the liveness detection into a larger flow:
class VerificationFlow extends StatefulWidget {
@override
_VerificationFlowState createState() => _VerificationFlowState();
}
class _VerificationFlowState extends State<VerificationFlow> {
int _currentStep = 0;
String? _sessionId;
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _currentStep,
children: [
// Step 1: Instructions
InstructionScreen(
onContinue: () => setState(() => _currentStep = 1),
),
// Step 2: Liveness Detection
LivenessDetectionScreen(
cameras: cameras,
onLivenessCompleted: (sessionId, isSuccessful, result) {
if (isSuccessful) {
setState(() {
_sessionId = sessionId;
_currentStep = 2;
});
}
},
),
// Step 3: Verification Complete
VerificationCompleteScreen(
sessionId: _sessionId,
onContinue: () => Navigator.pop(context),
),
],
),
);
}
}For even more control, you can use the controller directly:
class CustomLivenessScreen extends StatefulWidget {
@override
_CustomLivenessScreenState createState() => _CustomLivenessScreenState();
}
class _CustomLivenessScreenState extends State<CustomLivenessScreen> {
late LivenessController _controller;
@override
void initState() {
super.initState();
_controller = LivenessController(
cameras: cameras,
config: LivenessConfig(...),
theme: LivenessTheme(...),
onLivenessCompleted: (sessionId, isSuccessful, result) {
// Handle completion
},
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider.value(
value: _controller,
child: Consumer<LivenessController>(
builder: (context, controller, _) {
return Scaffold(
body: Stack(
children: [
// Your custom UI...
if (controller.currentState == LivenessState.completed)
// Show success UI
],
),
);
},
),
);
}
}ChallengeType.blink- Verify that the user can blinkChallengeType.turnLeft- Verify that the user can turn their head leftChallengeType.turnRight- Verify that the user can turn their head rightChallengeType.tiltUp- Verify that the user can tilt their head upChallengeType.tiltDown- Verify that the user can tilt their head downChallengeType.smile- Verify that the user can smileChallengeType.nod- Verify that the user can nod their headChallengeType.Zoom- The user needs to move their face closer to the camera, filling the oval.ChallengeType.normal- Checks whether the user's face is centered. Ideal for taking a photo of the user.
This package implements several advanced, configurable anti-spoofing measures to provide a robust defense against common presentation attacks. While some checks act as non-blocking flags, the motion correlation check determines the final success of the verification.
Upon completion, the onLivenessCompleted and onFinalImageCaptured callbacks return a detailed metadata map with the results.
Both callbacks provide a metadata map which may contain an antiSpoofingDetection key. This key holds a nested map with the following boolean flags:
motionCorrelationCheckFailed: The only blocking check by default. Iftrue, the overallisSuccessfulresult of the liveness check will befalse. This occurs if the head moves significantly but the device does not.screenGlareDetected: A non-blocking flag.trueif potential screen glare was detected on the user's face.lackOfFacialContoursDetected: A non-blocking flag.trueif the system failed to detect a sufficient number of facial contours, which could indicate a mask.
This check analyzes the camera feed for bright, reflective spots. It acts as a non-blocking flag in the final result.
Configuration:
enableScreenGlareDetection: Set tofalseto disable this check. (Default:true)glareBrightnessFactor: Multiplier for the average brightness to set the dynamic glare threshold. (Default:3.0)minBrightPercentage/maxBrightPercentage: The minimum and maximum percentage of bright pixels required to trigger the glare detection. (Defaults:0.05and0.30)
This is a powerful defense that determines the final success of the verification. To prevent false positives from minor tremors, it uses the standard deviation of head angles to detect significant movement. It ensures head and device movements are correlated.
Configuration:
enableMotionCorrelationCheck: Set tofalseto disable this check. (Default:true)significantHeadMovementStdDev: The standard deviation threshold for head movement to be considered significant. A higher value is more tolerant. (Default:5.0)minDeviceMovementThreshold: The minimum amount of device motion required to pass the check if significant head motion is detected. (Default:0.5)failOnMotionCorrelationFailedAtTheEnd: Whentrue, a failure in the motion correlation check will cause the overall liveness verification to be considered unsuccessful. Whenfalse, the check will still run and its result will be available in theantiSpoofingDetectionmetadata, but it will not block the overall success of the session. (Default:true)
This check verifies the integrity of facial contours and acts as a non-blocking flag in the final result.
Configuration:
enableContourAnalysisOnCentering: Whentrue, performs the contour check during the initial face centering step. (Default:true)contourChallengeTypes: A list ofChallengeTypewhere the contour check should also be performed (e.g.,ChallengeType.blinkorChallengeType.smile).minRequiredSecondaryContours: The minimum number of secondary contours (e.g., nose bridge, cheeks, upper lip bottom, lower lip top, eyebrows) that must be detected for the check to pass. This makes the detection tolerant to minor imperfections. (Default:5)
Example:
LivenessConfig(
// ... other settings
enableContourAnalysisOnCentering: true,
contourChallengeTypes: [
ChallengeType.blink,
ChallengeType.smile,
],
minRequiredSecondaryContours: 5, // Requires 5 out of 10 secondary contours to be present
)To prevent "swap attacks" (where a real user starts the session but then swaps to a photo/video), it is highly recommended to perform a face check at the beginning and at the end of the session.
This strategy "sandwiches" the liveness challenges between two ChallengeType.normal checks. The package can automatically insert these checks for random challenge sequences.
Configuration:
sandwichNormalChallenge: Whentrue, automatically adds aChallengeType.normalat the start and end of the randomly generated challenge list. (Default:falsefor backward compatibility)
Manual Configuration Note:
If you are providing a custom list of challengeTypes instead of using random generation, it is strongly recommended that you manually add ChallengeType.normal as the first and last items in your list.
Example:
LivenessConfig(
// ... other settings
enableContourAnalysisOnCentering: true,
contourChallengeTypes: [
ChallengeType.blink,
ChallengeType.smile,
],
minRequiredSecondaryContours: 5, // Requires 5 out of 10 secondary contours to be present
// Automatically add normal check at start and end
sandwichNormalChallenge: true,
)Check out our demo video to see the package in action!
Contributions are welcome! Feel free to submit a pull request.
This project is licensed under the MIT License - see the LICENSE file for details.
