flutter_liveness 2.0.0
flutter_liveness: ^2.0.0 copied to clipboard
On-device face liveness detection for Flutter using a MobileNetV2 model. Detect spoof attacks from photos and videos, no internet required.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter_liveness/flutter_liveness.dart';
import 'package:image/image.dart' as imglib;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'flutter_liveness demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple,
),
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
/// Replace with your face crop (asset, file or camera frame).
static const _sampleAsset = 'assets/sample_face_2.jpg';
FlutterLiveness? _liveness;
String _message = 'Tap ▶ to analyze';
bool _isLoading = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
_createLiveness();
});
}
@override
void dispose() {
_liveness?.dispose();
super.dispose();
}
Future<void> _createLiveness() async {
setState(() => _isLoading = true);
final liveness = await FlutterLiveness.create();
if (!mounted) {
await liveness.dispose();
return;
}
setState(() {
_liveness = liveness;
_isLoading = false;
});
}
Future<void> _run() async {
final liveness = _liveness;
if (liveness == null) return;
setState(() => _isLoading = true);
String message;
try {
final data = await rootBundle.load(_sampleAsset);
final face = imglib.decodeImage(
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes),
);
if (face == null) {
message = 'Could not decode $_sampleAsset';
} else {
final result = await liveness.analyze(face);
message = [
'Liveness: ${result.isLive ? 'LIVE' : 'SPOOF'}',
'Score: ${result.score.toStringAsFixed(3)}',
'Laplacian: ${result.laplacian}',
'Duration: ${result.duration.inMilliseconds} ms',
].join('\n');
}
} on FlutterError {
// Thrown by rootBundle when the asset is missing.
message = 'Add a face photo at example/$_sampleAsset';
}
if (!mounted) return;
setState(() {
_message = message;
_isLoading = false;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('flutter_liveness demo'),
),
body: Center(
child: _isLoading
? const CircularProgressIndicator()
: Text(
_message,
textAlign: TextAlign.center,
),
),
floatingActionButton: FloatingActionButton(
onPressed: _isLoading ? null : _run,
child: const Icon(Icons.play_arrow),
),
);
}
}