vidvliveness_flutter_plugin 1.0.7 copy "vidvliveness_flutter_plugin: ^1.0.7" to clipboard
vidvliveness_flutter_plugin: ^1.0.7 copied to clipboard

Flutter plugin to run native android and ios liveness sdks

example/lib/main.dart

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:vidvliveness_flutter_plugin/vidvliveness_flutter_plugin.dart';
import 'package:pretty_http_logger/pretty_http_logger.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: LivenessPage(),
    );
  }
}

class LivenessPage extends StatefulWidget {
  @override
  _LivenessPageState createState() => _LivenessPageState();
}

class _LivenessPageState extends State<LivenessPage> {
  final String baseURL = 'https://www.valifystage.com/';
  final String bundleKey = 'ad44eb94ca6747beaf99eef02407221f';
  final String userName = 'mobileusername';
  final String password = '3B8uGe8bNTquN84';
  final String clientID = 'aKM21T4hXpgHFsgNJNTKFpaq4fFpoQvuBsNWuZoQ';
  final String clientSecret = 'r0tLrtxTue8c4kNmPVgaAFNGSeCWvL4oOZfBnVXoQe2Ffp5rscXXAAhX50BaZEll8ZRtr2BlgD3Nk6QLOPGtjbGXYoCBL9Fn7QCu5CsMlRKDbtwSnUAfKEG30cIv8tdW';

  //  final String baseURL = "https://www.yfilav.com";
  // final String userName = "iosteam";
  // final String password = "dGsS#pj3wTkJjxG";
  // final String clientID = "k9zsWUI8hTmhadldFl98NNKlmDCYz6wa87GrhtEX";
  // final String clientSecret = "gyqKT05CMIVvmwZ5USJyR0OSL9dGJJfERt6Nlh3IqJNgrhUUAegid6sB3Hnu4cvLiPaEBvjoxv7HOMxvCwDjB4gMLgGShp2gqw1NJKW6lwZxncVuOa8XoMeX217L5pZ0";
  // final String bundleKey = "80f0ea4958a04685bf016a6ce10cff83";
  // final String hmacBundle = "46fadad8ebc0e2836f49439ee65caa4b42eb2bb1741e6cc69fd7c4024dda34e10a070c1fd8f855c99359c57c110c242e7685432f70504696b6f9ecbd749da8c3";

  String _livenessResult = '';
  String base64Image = "";
  String imagePicked = "No Image Picked";

  Future<String?> getToken() async {
    final String url = '$baseURL/api/o/token/';
    HttpWithMiddleware httpWithMiddleware = HttpWithMiddleware.build(middlewares: [
      HttpLogger(logLevel: LogLevel.BODY),
    ]);
    final Map<String, String> headers = {
      'Content-Type': 'application/x-www-form-urlencoded',
    };

    final String body =
        'username=$userName&password=$password&client_id=$clientID&client_secret=$clientSecret&grant_type=password';

    final http.Response response = await httpWithMiddleware.post(
      Uri.parse(url),
      headers: headers,
      body: body,
    );

    if (response.statusCode == 200) {
      final Map<String, dynamic> jsonResponse = json.decode(response.body);
      return jsonResponse['access_token'];
    } else {
      print('Failed to retrieve token: ${response.statusCode}');
      return null;
    }
  }

  Future<void> pickImage() async {
    final ImagePicker _picker = ImagePicker();
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);

    if (image != null) {
      final bytes = await File(image.path).readAsBytes();
      final base64 = base64Encode(bytes);
      setState(() {
        imagePicked = "Image Picked Successfully";
        base64Image = base64;
      });
    } else {
      setState(() {
        base64Image = '';
      });
    }
  }

  Future<void> startLiveness() async {
    String? token;

    try {
      token = await getToken();
      if (token == null) {
        setState(() {
          _livenessResult = 'Failed to get token';
        });
        return;
      }
    } catch (e) {
      setState(() {
        _livenessResult = 'Error retrieving token: $e';
      });
      return;
    }
    Map<String, dynamic> params = {
      'base_url': baseURL,
      'access_token': token,
      'bundle_key': bundleKey,
      'language': 'en',
      'liveness_time_per_action': '10',
      'liveness_number_of_instructions': '5',
      'enable_smile': false,
      'enable_look_right': true,
      'enable_close_eyes': true,
      'enable_voiceover': true,
      'primary_color': '#FF5733',
      'show_error_message': true,
      'facematch_image': base64Image,
    };

    try {
      final result = await VidvlivenessFlutterPlugin.startLiveness(params);
      setState(() {
        _livenessResult = result.toString();
      });
    } catch (e) {
      setState(() {
        _livenessResult = 'Error: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Liveness Detection'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            ElevatedButton(
              onPressed: pickImage,
              child: Text('Select Image from Gallery'),
            ),
            SizedBox(height: 10),
            if (base64Image.isNotEmpty)
              Text(
                'Image Selected',
                style: TextStyle(color: Colors.green),
              ),
            ElevatedButton(
              onPressed: startLiveness,
              child: Text('Start Liveness Detection'),
            ),
            SizedBox(height: 20),
            SingleChildScrollView(
              child: Column(
                children: [
                  Text('Liveness Result: $_livenessResult'),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}