authme_ekyc_sdk 2.8.16
authme_ekyc_sdk: ^2.8.16 copied to clipboard
A Flutter package of ekyc of authme.
Authme eKYC Flutter SDK implementation guide #
Welcome to the AuthMe eKYC SDK! This document will guide you through the initialization, configuration, and usage of the SDK, ensuring you can successfully integrate identity verification functionality into your Flutter application.
Table of Contents #
- Getting Started
- Setup
- Initialization
- Data Structure
- Configuration Options
- Features & Usage Examples
- Basic Workflow Example
- Error Handling
- Resource Cleanup
Getting Started #
This guide will help you complete the following steps:
- Install the SDK – Set up the necessary dependencies.
- Initialize the SDK – Configure and prepare the SDK for use.
- Use identity verification features – Capture and verify identity documents.
- Handle verification results – Process and analyze returned data.
By following this guide, you will be able to successfully integrate AuthMe eKYC SDK into your Flutter application and use it for seamless identity verification.
Setup #
1. Install the SDK #
To integrate the SDK into your Flutter application, add the following dependency to your pubspec.yaml file:
dependencies:
authme_ekyc_sdk: ^x.y.z
Then, run the following command to install the package:
flutter pub get
2. Import the Package #
To use the SDK, import it into your Dart files where required:
import 'package:authme_ekyc_sdk/ekyc_sdk_plugin_bridge.dart';
3. Android Setup #
Ensure your Android project meets the following requirements:
- Use Kotlin 1.7.10 or later.
- Set API level 24 (Android 7.0) or higher in
android/app/build.gradle.
android {
defaultConfig {
minSdkVersion 24
}
}
Handling OutOfMemoryError #
If you encounter an OutOfMemoryError during Gradle builds, add the following setting to your android/gradle.properties:
org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError
You may adjust the memory size based on your project requirements. Refer to the official Gradle documentation for default values: Gradle Build Environment.
4. iOS Setup #
Update Podfile #
Modify ios/Podfile to specify the minimum required iOS version and required pod sources:
platform :ios, '13.0'
source '<https://github.com/AuthMe01/PodSpecs.git>'
source '<https://github.com/CocoaPods/Specs.git>'
Add Required SDK Dependencies #
Ensure the following dependencies are included in your Podfile under the Runner target:
target 'Runner' do
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
pod 'AuthMe', '= 2.7.33'
pod 'AuthMeUI', '= 2.7.33'
pod 'AuthmeNFCKit', '= 1.0.15'
target 'RunnerTests' do
inherit! :search_paths
end
end
Update Pods #
Run the following command inside the ios/ directory to update the pod dependencies:
pod update
Configure Permissions #
Update Info.plist to include descriptions for required permissions:
<key>NSCameraUsageDescription</key>
<string>Allow camera access for identity verification</string>
<key>NSMicrophoneUsageDescription</key>
<string>Allow microphone access for identity verification</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Allow access to photo library</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Allow location access for identity verification</string>
With these steps completed, your SDK setup is ready for initialization and use in your application.
Initialization #
1. Create an SDK Instance #
To begin, create an instance of the AuthMeSdk:
final AuthmeSdk _authMeSdk = AuthmeSdk();
2. Initialize the SDK #
Call the initialize method with your required parameters:
_authMeSdk.initialize(
"<https://your.server.url>", // Your backend API URL eg. https//:api.authme.com/
"your_activate_token", // Activation token JWT token provided with Certificate
"your_activate_certificate", // Activation certificate
showStatement: true, // (Android only) Whether to show a user statement
);
Example Implementation #
Here is a full example implementation that includes initialization, handling results, and confirming scan results:
class _AuthMeHomePageState extends State<AuthMeHomePage> {
final AuthmeSdk _authMeSdk = AuthmeSdk();
late StreamSubscription _resultSubscription;
String? _accessToken;
@override
void initState() {
super.initState();
_resultSubscription = _authMeSdk.resultStream.listen(
handleResult,
onError: handleError,
);
_fetchToken();
_initSDK();
}
void _handleResult(Map<String, dynamic> result) {
if (result.containsKey('result')) {
final resultMap = result['result'];
if (resultMap is Map) {
final data = resultMap['data'];
final images = resultMap['images'];
if (data is Map) {
Map<String, dynamic> modifications = Map.from(data);
modifications['address'] = 'new address';
_authMeSdk.confirmScanResult(modifications).then((_) {
log('Scan result confirmed');
}).catchError((error) {
log('Failed to confirm scan result: $error');
});
}
}
} else if (result.containsKey('error')) {
log("Error: ${result['error']}");
}
}
Future<void> _fetchToken() async {
_accessToken = getTokenFromServer();
}
void _initSDK() {
_authMeSdk.initialize(
"api domain",
"YOUR_ACTIVATE_TOKEN",
"-----BEGIN CERTIFICATE-----\\nYOUR_CERTIFICATE_CONTENT\\n-----END CERTIFICATE-----\\n",
);
}
void _startAuthme() async {
if (_accessToken != null) {
await _authMeSdk.startFeature(
_accessToken!,
AuthmeFeature.TWID,
needConfirm: true,
isResultPageDisplayable: true,
);
}
}
@override
void dispose() {
_resultSubscription.cancel();
_authMeSdk.dispose();
super.dispose();
}
}
Parameter Descriptions #
| Parameter | Type | Description |
|---|---|---|
serverURL |
String |
The server URL for API communication. |
activateToken |
String |
Token required to activate the SDK. |
activateCertificate |
String |
Certificate required for activation. |
showStatement |
bool |
(Android only) Whether to display a user agreement before usage. |
Possible Initialization Errors #
If the SDK fails to initialize, it may return one of the following errors:
| Error Code | Description |
|---|---|
AUTHME_ERROR_001 |
Invalid or missing parameters (serverURL, activateToken, activateCertificate). |
AUTHME_ERROR_002 |
SDK activation failed due to network issues or expired token. |
AUTHME_ERROR_003 |
Missing root view controller on iOS during initialization. |
If an error occurs, check the provided parameters and ensure that your network connection is stable. If issues persist, contact AuthMe technical support.
After successful initialization, the SDK is ready to process identity verification requests.
Data Structure #
The SDK returns data in the form of Map<String, dynamic> with the following structure:
{
"result": {
"data": {
"dateOfBirth": "1968-02-02", // YYYY-MM-DD
"dateOfIssue": "2005-07-01", // YYYY-MM-DD
"gender": "female", // "male", "female".
"givenName": "小明", // Given name
"idNumber": "A123456789", // National ID number or "" if not available
"issueCity": "臺北市", // City where document was issued
"issueReason": "初發", // "初發", "換發", "補發"
"name": "陳小明", // Full name
"surname": "陳", // Surname (Family name)
"address": "臺北市內湖區民生里5鄰民權東路16弄18號", // Full address
"father": "陳德明", // Father's name
"militaryService": "", // "Completed", "Exempted" or empty if not applicable
"mother": "吳春美", // Mother's name
"placeOfBirth": "臺北市", // Place of birth
"serialNumber": "0000000105", // Document serial number
"spouse": "金大昇" // Spouse's name (if applicable)
},
"images": {
"frontImage": "base64ImageString", // Base64 encoded front image
"backImage": "base64ImageString", // Base64 encoded back image
"frontCropImage": "base64ImageString", // Cropped front image
"backCropImage": "base64ImageString" // Cropped back image
}
}
}
Field Descriptions #
Data (data) #
| Field | Type | Description |
|---|---|---|
dateOfBirth |
String | User’s date of birth in YYYY-MM-DD format. |
dateOfIssue |
String | Document issue date in YYYY-MM-DD format. |
gender |
String | User’s gender (male, female, or other). |
givenName |
String | User’s given name. |
idNumber |
String | National ID number or "N/A" if unavailable. |
issueCity |
String | City where the document was issued. |
issueReason |
String | Document issuance reason (初發, 換發, 補發). |
name |
String | Full name of the user. |
surname |
String | Surname of the user. |
address |
String | Complete residential address. |
father |
String | User’s father’s name. |
militaryService |
String | Military service status (Completed, Exempted, or empty). |
mother |
String | User’s mother’s name. |
placeOfBirth |
String | User’s place of birth. |
serialNumber |
String | Unique serial number of the document. |
spouse |
String | User’s spouse name if applicable. |
Images (images) #
| Field | Type | Description |
|---|---|---|
frontImage |
String | Base64-encoded full front image of the document. |
backImage |
String | Base64-encoded full back image of the document. |
frontCropImage |
String | Base64-encoded cropped front image with text fields. |
backCropImage |
String | Base64-encoded cropped back image with text fields. |
Field Descriptions #
(Existing field descriptions as previously detailed...)
Liveness Data Structure #
The SDK also returns liveness detection results in the following format:
{
"result": {
"data": {
"livenessResult": "success" // "success", "failed", "unknown"
}
}
}
Liveness Fields #
| Field | Type | Description |
|---|---|---|
livenessResult |
String | Liveness detection result (success, failed, unknown). |
This data structure ensures that all relevant identity verification details are extracted and formatted properly. The OCR Data Structure provides detailed document recognition, while the Liveness Data Structure ensures biometric verification of the user.
Configuration Options #
This section details the available configuration options when using the AuthMe eKYC SDK. These options allow developers to customize the behavior of the SDK to fit their needs.
SDK Initialization Parameters #
The initialize method requires specific parameters to configure the SDK properly.
Example: #
_authMeSdk.initialize(
"<https://your.server.url>", // serverURL
"your_activate_token", // activateToken
"your_activate_certificate", // activateCertificate
showStatement: true, // Android-specific UI setting
);
Parameter Descriptions: #
| Parameter | Type | Description |
|---|---|---|
serverURL |
String | The URL of the backend server handling verification requests. |
activateToken |
String | Token required to activate the SDK. |
activateCertificate |
String | Certificate used to authenticate the activation process. |
showStatement |
bool | (Android only) Whether to display a consent statement before verification. |
Feature-Specific Configuration #
Each feature supports additional options when invoking startFeature.
Example: #
await _authMeSdk.startFeature(
accessToken,
AuthmeFeature.TWID,
requestCode: 1234,
needConfirm: true,
isResultPageDisplayable: true,
isResultEditable: true,
isFraudIntroEnable: true,
);
Parameter Descriptions: #
| Parameter | Type | Description |
|---|---|---|
accessToken |
String | The token used to authenticate API requests. |
feature |
AuthmeFeature | Specifies the document type or verification method. |
requestCode |
int | Custom request code to track the verification session. |
needConfirm |
bool | If true, manual confirmation of results is required. |
isResultPageDisplayable |
bool | If true, a results page is shown after verification. |
isResultEditable |
bool | If true, the user can edit verification results before confirmation. |
isFraudIntroEnable |
bool | If true, the fraud prevention introduction page is displayed. |
Localization Options #
The SDK supports localization to adapt to different languages.
_authMeSdk.setLocale("zh-TW"); // Example: Set language to Traditional Chinese
| Parameter | Type | Description |
|---|---|---|
locale |
String | Language setting (e.g., en-US, zh-TW, ja-JP). |
Logging and Debugging Options #
To enable debugging and log output:
_authMeSdk.enableDebug(true);
| Parameter | Type | Description |
|---|---|---|
enableDebug |
bool | Enables additional logging for troubleshooting. |
Error Handling Configuration #
If an error occurs during verification, handle it using error callback methods.
_authMeSdk.setErrorHandler((error) {
print("SDK Error: ${error.message}");
});
| Parameter | Type | Description |
|---|---|---|
setErrorHandler |
Function | Callback function to handle errors returned by the SDK. |
Customizing UI and Flow #
The SDK allows UI customization for better integration into your application.
_authMeSdk.customizeUI({
"backgroundColor": "#FFFFFF",
"buttonColor": "#0000FF",
});
| Parameter | Type | Description |
|---|---|---|
backgroundColor |
String | Hex color for the background of the verification page. |
buttonColor |
String | Hex color for action buttons. |
Features & Usage Examples #
Supported Features AuthMe eKYC SDK provides multiple identity verification features, allowing developers to select functionalities based on their needs. The supported features are:
| Feature Name | Description |
|---|---|
TWIDFraud |
Taiwan National ID with fraud detection. |
TWID |
Taiwan National ID verification. |
TWDriverLicense |
Taiwan Driver’s License verification. |
TWHealth |
Taiwan Health Insurance Card verification. |
Passport |
International passport verification. |
NFCPassport |
NFC-enabled passport verification. |
Liveness |
AI-based liveness detection. |
Other Features |
More identity verification functionalities to be added. |
OCR-Based Document Recognition #
Invoke Method #
Future<void> startOCRVerification() async {
final String accessToken = "your_access_token";
await _authMeSdk.startFeature(
accessToken,
AuthmeFeature.TWID,
needConfirm: true,
isResultPageDisplayable: true,
);
}
Handling OCR Results #
void handleOCRResult(Map<String, dynamic> result) {
if (result.containsKey('result')) {
final data = result['result']['data'];
final images = result['result']['images'];
if (data != null) {
print("OCR Data: ${data.toString()}");
}
if (images != null) {
print("Document Images: ${images.toString()}");
}
} else {
print("OCR result is missing.");
}
}
Confirming OCR Results #
If needConfirm is set to true, developers must confirm the scan results before proceeding. The data should be structured as follows:
Future<void> confirmOCRResults(Map<String, dynamic> modifications) async {
try {
await _authMeSdk.confirmScanResult({
"data": modifications
});
print("OCR result confirmed successfully.");
} catch (error) {
print("Failed to confirm OCR result: $error");
}
}
Liveness Detection #
Invoke Method #
Future<void> startLivenessDetection() async {
final String accessToken = "your_access_token";
await _authMeSdk.startFeature(
accessToken,
AuthmeFeature.Liveness,
needConfirm: false,
);
}
Handling Liveness Results #
void handleLivenessResult(Map<String, dynamic> result) {
if (result.containsKey('result')) {
final livenessData = result['result']['data'];
if (livenessData != null && livenessData['livenessResult'] == 'success') {
print("Liveness detection passed.");
} else {
print("Liveness detection failed.");
}
}
}
NFC Passport Verification #
Invoke Method #
Future<void> startNFCPassportVerification() async {
final String accessToken = "your_access_token";
await _authMeSdk.startFeature(
accessToken,
AuthmeFeature.NFCPassport,
needConfirm: true,
isResultPageDisplayable: true,
);
}
Handling NFC Results #
void handleNFCPassportResult(Map<String, dynamic> result) {
if (result.containsKey('result')) {
final data = result['result']['data'];
final images = result['result']['images'];
if (data != null) {
print("NFC Passport Data: ${data.toString()}");
}
if (images != null) {
print("Scanned Images: ${images.toString()}");
}
} else {
print("NFC passport result is missing.");
}
}
Confirming NFC Results #
If needConfirm is set to true, developers must confirm the scan results before proceeding. The data should be structured as follows:
Future<void> confirmNFCResults(Map<String, dynamic> modifications) async {
try {
await _authMeSdk.confirmScanResult({
"data": modifications
});
print("NFC result confirmed successfully.");
} catch (error) {
print("Failed to confirm NFC result: $error");
}
}
Permissions #
For Android, the SDK automatically prompts users for required permissions during the identity verification process. There is no need to manually define runtime permissions in your application.
These examples provide clear guidelines on how to invoke the SDK's core features and handle verification results.
Handling Verification Results & Confirming Scan Results #
This section provides a detailed breakdown of how to handle the returned results from the AuthMe eKYC SDK and confirm results when needConfirm is set to true.
Example of a Typical SDK Response #
When an OCR or NFC verification process completes, the SDK returns a structured JSON response.
Sample Response JSON: #
{
"result": {
"data": {
"dateOfBirth": "1968-02-02",
"dateOfIssue": "2005-07-01",
"gender": "female",
"givenName": "筱樣",
"idNumber": "N/A",
"issueCity": "臺北市",
"issueReason": "換發",
"name": "陳筱樣",
"surname": "陳",
"address": "臺北市內湖區民生里5鄰民權東路16弄18號",
"father": "陳德明",
"militaryService": "",
"mother": "吳春美",
"placeOfBirth": "臺北市",
"serialNumber": "0000000105",
"spouse": "金大昇"
},
"images": {
"frontImage": "base64ImageString",
"backImage": "base64ImageString",
"frontCropImage": "base64ImageString",
"backCropImage": "base64ImageString"
}
}
}
Processing the SDK Response #
Once verification is complete, developers need to handle the response data and process the extracted fields accordingly.
Dart Implementation: #
void handleResult(Map<String, dynamic> result) {
final resultData = result['result'] as Map<String, dynamic>?;
if (resultData == null) {
print('No result data available');
return;
}
final data = resultData['data'] as Map<String, dynamic>?;
final images = resultData['images'] as Map<String, dynamic>?;
if (data != null) processData(data);
if (images != null) processImages(images);
}
Extracting and Processing Data Fields #
void processData(Map<String, dynamic> data) {
final name = data['name'] as String?;
final address = data['address'] as String?;
final dateOfBirth = data['dateOfBirth'] as String?;
final idNumber = data['idNumber'] as String?;
print("Extracted Data: Name: $name, Address: $address, DOB: $dateOfBirth, ID: $idNumber");
}
Processing Image Data (Base64 Format) #
void processImages(Map<String, dynamic> images) {
final frontImage = images['frontImage'] as String?;
final backImage = images['backImage'] as String?;
final frontCropImage = images['frontCropImage'] as String?;
final backCropImage = images['backCropImage'] as String?;
if (frontImage != null) processFrontImage(frontImage);
if (backImage != null) processBackImage(backImage);
if (frontCropImage != null) processFrontCropImage(frontCropImage);
if (backCropImage != null) processBackCropImage(backCropImage);
}
Confirming Scan Results (needConfirm: true) #
If needConfirm is set to true, developers must send back the scanned results to confirm verification.
Example of Modifying and Confirming Results #
Future<void> confirmScanResults(Map<String, dynamic> modifications) async {
try {
await _authMeSdk.confirmScanResult({
"data": modifications
});
print("Scan result confirmed successfully.");
} catch (error) {
print("Failed to confirm scan result: $error");
}
}
Example JSON Payload for Confirming Results #
{
"data": {
"name": "陳筱樣",
"address": "臺北市內湖區民生里5鄰民權東路16弄18號",
"dateOfBirth": "1968-02-02",
"idNumber": "F123456789"
}
}
Basic Workflow Example #
This section outlines the complete workflow for integrating and using the AuthMe eKYC SDK in a Flutter application. Each step is explained in detail to ensure clarity.
Step 1: Install and Initialize the SDK #
- Add the required dependency in
pubspec.yaml. - Run
flutter pub getto install the package. - Import the SDK in your Dart file.
- Initialize the SDK using the
initializemethod.
Step 2: Start a Verification Process #
To start an identity verification process, select the appropriate feature and invoke the startFeature method.
Example for OCR-Based Document Recognition #
Future<void> startOCRVerification() async {
final String accessToken = "your_access_token";
await _authMeSdk.startFeature(
accessToken,
AuthmeFeature.TWID,
needConfirm: true,
isResultPageDisplayable: true,
);
}
accessToken: Required authentication token for API access.feature: Specifies the document type to be verified.needConfirm: Iftrue, manual confirmation is required before finalizing the result.isResultPageDisplayable: Iftrue, a result page will be displayed after verification.
Step 3: Handling Verification Results #
Once verification is complete, the SDK will return a result. Handle the result by extracting data and images.
Handling OCR Results #
void handleOCRResult(Map<String, dynamic> result) {
if (result.containsKey('result')) {
final data = result['result']['data'];
final images = result['result']['images'];
if (data != null) {
print("OCR Data: ${data.toString()}");
}
if (images != null) {
print("Document Images: ${images.toString()}");
}
} else {
print("OCR result is missing.");
}
}
Handling NFC Passport Results #
void handleNFCPassportResult(Map<String, dynamic> result) {
if (result.containsKey('result')) {
final data = result['result']['data'];
final images = result['result']['images'];
if (data != null) {
print("NFC Passport Data: ${data.toString()}");
}
if (images != null) {
print("Scanned Images: ${images.toString()}");
}
} else {
print("NFC passport result is missing.");
}
}
Step 4: Confirming Results When needConfirm is true #
If needConfirm is enabled, you must confirm the results before finalizing the verification process.
Confirming OCR Results #
Future<void> confirmOCRResults(Map<String, dynamic> modifications) async {
try {
await _authMeSdk.confirmScanResult({
"data": modifications
});
print("OCR result confirmed successfully.");
} catch (error) {
print("Failed to confirm OCR result: $error");
}
}
Confirming NFC Results #
Future<void> confirmNFCResults(Map<String, dynamic> modifications) async {
try {
await _authMeSdk.confirmScanResult({
"data": modifications
});
print("NFC result confirmed successfully.");
} catch (error) {
print("Failed to confirm NFC result: $error");
}
}
- The data should be structured as a JSON object with key-value pairs matching the expected fields.
- Ensure the modified data is accurate before calling
confirmScanResultto prevent validation failures.
Step 5: Handling Errors and Logging #
Proper error handling is essential to ensure smooth integration. Use try-catch blocks to catch potential issues.
Example Error Handling for OCR Verification #
try {
await _authMeSdk.startFeature(accessToken, AuthmeFeature.TWID);
} on PlatformException catch (e) {
print("Error: ${e.message}");
}
Step 6: Cleanup and Resource Management #
Once the verification process is complete, release SDK resources to avoid memory leaks.
@override
void dispose() {
_authMeSdk.dispose();
super.dispose();
}
This ensures the SDK does not retain unnecessary memory allocations after use.
Error Handling #
Error handling is essential to ensure a smooth user experience and debugging process when integrating the AuthMe eKYC SDK. Below are common errors, their causes, and how to handle them effectively.
Common SDK Errors & Solutions #
| Error Code | Description | Possible Causes | Resolution |
|---|---|---|---|
AUTHME_ERROR_001 |
Invalid or missing parameters (e.g., serverUrl, activateToken, accessToken). |
Missing or incorrect parameters during SDK initialization or API request. | Verify that all required parameters are provided and correctly formatted. |
AUTHME_ERROR_002 |
Scan process failed. | Network issues, expired token, or internal error. | Check network connectivity and retry the scan. |
AUTHME_ERROR_003 |
Plugin not attached or root view controller not found during SDK initialization. | Insufficient memory on the device or unexpected system error. | Restart SDK initialization and ensure the app has sufficient memory. |
AUTHME_ERROR_004 |
Invalid OCR or feature parameters. | Missing required fields such as token, feature, or OCR parameters. |
Validate all required parameters before calling the feature. |
AUTHME_ERROR_005 |
Invalid or unsupported document type. | Document type is not supported by the SDK. | Ensure the selected document type is valid and listed in supported features. |
AUTHME_ERROR_006 |
needConfirm set to false while attempting manual confirmation. |
Incorrect configuration settings. | Check and update needConfirm settings. |
AUTHME_ERROR_007 |
Scan result confirmation failed. | Error while calling confirmScanResult. |
Retry the scan result confirmation and verify the data structure. |
AUTHME_ERROR_008 |
No available OCR result. | OCR process did not generate a result. | Retry the scanning process. |
AUTHME_ERROR_009 |
Missing locale parameter in SDK configuration. |
Locale parameter not provided. | Include locale in the SDK configuration request. |
AUTHME_ERROR_010 |
Invalid or unsupported locale format. |
Incorrectly formatted locale value. | Use a valid locale format (e.g., en-US, zh-TW). |
AUTHME_ERROR_011 |
UI configuration parameters are invalid. | Incorrect UI settings. | Ensure all UI parameters match the expected format. |
AUTHME_ERROR_012 |
Missing controller. | The Coordinator view controller was deallocated. |
Contact the AuthMe support team for troubleshooting. |
AUTHME_ERROR_013 |
Presenter not found in the view hierarchy. | UI component lost reference during execution. | Ensure that the view is properly attached and not removed prematurely. |
Implementing Error Handling in Code #
Developers should use try-catch blocks to handle potential errors when calling SDK methods.
Example: Handling Errors When Starting a Verification Process #
try {
await _authMeSdk.startFeature(accessToken, AuthmeFeature.TWID);
} on PlatformException catch (e) {
print("Error: ${e.message}");
}
Example: Handling Errors When Confirming Scan Results #
Future<void> confirmScanResults(Map<String, dynamic> modifications) async {
try {
await _authMeSdk.confirmScanResult({
"data": modifications
});
print("Scan result confirmed successfully.");
} catch (error) {
print("Failed to confirm scan result: $error");
}
}
Handling Network Errors #
Since the SDK relies on external API calls, it is essential to handle network-related issues gracefully.
Example: Handling Network Errors #
Future<void> safeNetworkCall(Function callFunction) async {
try {
await callFunction();
} on SocketException catch (_) {
print("Network error: Check your internet connection.");
} catch (e) {
print("Unexpected error: ${e.toString()}");
}
}
Graceful Recovery from Errors #
- Retry Mechanism: Implement a retry mechanism for recoverable errors like network failures.
- User Notification: Display meaningful error messages to guide users.
- Logging: Log errors for easier debugging and support requests.
- Error Reporting: Use monitoring tools to track error occurrences and improve system stability.
Resource Cleanup #
Proper resource management is crucial to prevent memory leaks and ensure smooth operation of the SDK. This section details how to correctly dispose of SDK resources when they are no longer needed.
Disposing SDK Resources #
Once the SDK is no longer required (e.g., when the user exits the verification screen), dispose of the instance to free up memory.
Example: Cleaning Up the SDK in dispose() #
@override
void dispose() {
_authMeSdk.dispose();
super.dispose();
}
- Why? This prevents memory leaks by releasing unused resources.
- When? Always call
dispose()when the SDK session ends.
Cancelling Stream Subscriptions #
If you are using real-time event listeners (such as StreamSubscription for result handling), cancel them before the widget is disposed.
Example: Cancelling Stream Listeners #
late StreamSubscription<Map<String, dynamic>> _resultSubscription;
@override
void initState() {
super.initState();
_resultSubscription = _authMeSdk.resultStream.listen(
handleResult,
onError: handleError,
);
}
@override
void dispose() {
_resultSubscription.cancel(); // Cancel the subscription
_authMeSdk.dispose(); // Release SDK resources
super.dispose();
}
- Why? Prevents memory leaks and unintended callbacks.
- When? Call
cancel()before disposing the SDK.
Releasing NFC Resources #
If using NFC verification (NFCPassport), ensure NFC-related processes are properly released to avoid conflicts with other NFC-dependent applications.
Example: Stopping NFC Scanning Manually #
void stopNFCScanning() {
_authMeSdk.stopNFCPassportScan();
print("NFC scanning stopped.");
}
- Why? Ensures NFC scanning does not interfere with other apps.
- When? Call
stopNFCPassportScan()when NFC verification completes or is canceled.
Ensuring Cleanup in Error Cases #
If an error occurs mid-verification, ensure cleanup actions still execute to maintain stability.
Example: Cleanup in Error Handling #
try {
await _authMeSdk.startFeature(accessToken, AuthmeFeature.TWID);
} catch (error) {
print("Error encountered: ${error.toString()}");
} finally {
_authMeSdk.dispose();
}
- Why? Ensures SDK is disposed even if an error occurs.
- When? Always handle cleanup in
finallyblocks where possible.
Best Practices for Resource Management #
- Always call
dispose()when the SDK is no longer in use. - Cancel active streams to prevent memory leaks.
- Manually stop NFC scanning if used.
- Use
finallyblocks to ensure cleanup happens even if an error occurs.
By following these best practices, you can prevent performance issues and maintain a stable application.