How to Build a Flutter Passport Scanner with NFC Chip Verification
1. Introduction
For many digital services, especially in the financial sector, onboarding requires more than simply scanning a passport and extracting its data. Banks, fintech companies, and other organizations use so-called Know Your Customer (KYC) procedures to verify user identities, prevent document fraud, and meet regulatory requirements.
To build a secure KYC process, businesses need to combine several identity verification technologies, including MRZ scanning, NFC chip reading, and face matching. These checks help establish whether the document is authentic and belongs to the person presenting it – and they should be performed entirely on the user’s device to prevent sensitive identity data from being exposed to external parties.
At OCR Studio, we develop exactly this kind of privacy-first, on-device identity verification technologies in line with our Zero-Trust KYC Manifesto. In today’s tutorial, we’ll show you how to integrate them into your Flutter application for iOS and Android to build a secure mobile KYC workflow that keeps sensitive customer data under your control.
2. SDK Architecture – structure, key objects
The package ocrstudiosdk_flutter is a thin Dart FFI mirror of the native C API: every class (OCRStudioSDKInstance, OCRStudioSDKSession, OCRStudioSDKImage, OCRStudioSDKResult, OCRStudioSDKProcessingConfig) holds a native object and releases it in dispose().
The lib structure in the OCRStudio Flutter SDK is as follows:
lib/
├── external.dart -- the only public import; re-exports
│ everything below
├── ocr_studio_sdk_instance.dart -- OCRStudioSDKInstance: createFromBuffer /
│ createFromPath / createStandalone,
│ createSession(signature, jsonParams),
│ description, libraryVersion, dispose()
├── ocr_studio_sdk_session.dart -- OCRStudioSDKSession: processImage(image),
│ processData(json), currentResult(),
│ registerConfig(config), reset/suspend/
│ resume, isLocked / unlockRequest /
│ unlock(key) (dynamic activation)
├── ocr_studio_sdk_image.dart -- OCRStudioSDKImage: fromFileBuffer,
│ fromSystemDecoderFile (mobile OS decoder,
│ HEIC + EXIF orientation), fromYUV,
│ fromBgra; rotateByNinety, flipHorizontal,
│ cropByRect. Max side: 25000 px
├── ocr_studio_sdk_result.dart -- OCRStudioSDKResult: serialize(),
│ targetsCount, isAllTargetsFinal,
│ borrowed target/item accessors
├── ocr_studio_sdk_processing_config.dart -- ProcessingConfig.fromBuffer/fromJson,
│ multi-step flows (kyc_config.json)
├── ocr_studio_sdk_exception.dart -- OCRStudioSDKException; use
│ OCRStudioSDKException.messageOf(e)
├── utils.dart -- internal helpers (string passing, error
│ unwrapping)
└── ffi/
├── ocr_bindings_generated.dart -- ffigen output; regenerate with
│ `dart run ffigen --config ffigen.yaml`
└── native_library.dart -- per-platform dlopen loaderCalls are synchronous and block the calling isolate, so the sample puts all native work in a single worker isolate:
- example/lib/engine_worker.dart – the worker. The only owner of native objects. Reads the .ocr bundle from app assets, creates the instance, sessions, images, results and frees them.
- example/lib/engine.dart – the Engine.instance singleton. Spawns the worker, sends it commands and awaits answers (request/response over IsolateChannel). Also holds the named session methods, the JSON field keys.
- example/lib/dto/ – plain data crossing the isolate boundary ImageData, OcrResult/OcrTarget/OcrDescription (a typed view over result.serialize() JSON), QuadData (document/field quadrangles for the camera overlay), PassportNfcResult (chip data).
- example/lib/nfc/passport_nfc.dart – BAC/PACE chip reading on top of dmrtd, plus MRZ key helpers.
Core OCRStudio Flutter SDK passport-reading pipeline:
Optical document recognition -> NFC chip reading -> Face comparison
3. Adding the Library
pubspec.yaml – add the package and declare the bundle in assets:
dependencies:
ocrstudiosdk_flutter:
path: ../ocr_flutter_sdk
flutter:
assets:
- assets/config/
Put the .ocr bundle in example/assets/config/. The package is an FFI plugin, so native libraries must live inside the plugin itself (see Setup below) – they are not embedded from your app.
Import in your project:
import 'package:ocrstudiosdk_flutter/external.dart';Android – AndroidManifest.xml:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.NFC" />Place libcocrstudiosdk.so in android/src/main/jniLibs/<abi>/ (arm64-v8a, armeabi-v7a, x86_64). The plugin’s minSdk is 24.
iOS – Info.plist:
<key>NSCameraUsageDescription</key>
<string>Camera is used to scan your passport MRZ and verify your identity.</string>
<key>NFCReaderUsageDescription</key>
<string>NFC is used to read the chip inside your passport.</string>Put cocrstudiosdk.xcframework into ocrstudiosdk_flutter (slices ios-arm64 and ios-arm64_x86_64-simulator,). It is vendored by ocrstudiosdk_flutter.podspec and the SPM binary target in Package.swift. Add the NFC entitlement and passport AID to Runner.entitlements:
<key>com.apple.developer.nfc.readersession.iso7816.select-identifiers</key>
<array><string>A0000002471001</string></array>License signature. Substitute your signature into _signature in example/lib/engine_worker.dart . Without it the bundle loads but createSession fails.
Reusable files from the sample
These are not part of the OCRStudio Flutter SDK API but are essential glue – copy them rather than reimplement:
- example/lib/engine_worker.dart – the isolate protocol; the sole owner of native objects.
- example/lib/engine.dart – the Engine singleton, session recipes (SessionParams), field keys (EngineFieldKeys).
- example/lib/dto/ – ocr_result, image_data, quad_data, passport_nfc_result.
- example/lib/nfc/passport_nfc.dart – chip reading and MRZ key helpers.
4. Initializing the Engine and Creating a Session
Engine initialization
In the OCRStudio Flutter SDK Engine.instance.init() spawns the worker isolate, passing it the RootIsolateToken. The worker initializes BackgroundIsolateBinaryMessenger, reads the first *.ocr asset from rootBundle itself, and creates the native instance with lazy initialization:
final instance = OCRStudioSDKInstance.createFromBuffer(bundleBytes, {
'enable_lazy_initialization': true,
'enable_delayed_initialization': false,
});init() then fills:
- engine.config – the bundle description JSON;
- engine.version – native library version;
- engine.sessionTypes – session types the bundle supports (document_recognition, video_recognition, face_matching, liveness_detection, text_recognition…);
Creating a session
Engine exposes one named method per product flow — each builds the full JSON settings map internally :
await engine.createVideoSession(mode: 'anypassport', masks: ['*']);which expands to:
{
"session_type": "video_recognition",
"target_group_type": "anypassport",
"target_masks": ["*"],
"output_modes": "field_geometry",
"options": {
"extractTemplateImages": "true",
"fraudAttemptEnabled": "true",
"currentDate": "dd.MM.yyyy",
"sessionTimeout": "5.0",
"oneShotKYCEnabled": "false"
}
}In the worker this becomes instance.createSession(signature, jsonParams). The previous session is disposed first – creating a new session always closes the old one, so you never need to pair createSession with a manual dispose.
Target Group Type “anypassport” setting allows for the identification and recognition of a passport type. To determine whether a given passport’s chip is supported for NFC reading, you must use the document recognition mode rather than the MRZ-specific mode. For example, you can use targetGroupType “default” and targetMasks “mrz.*” to read the MRZ, but in this case, it will not be possible to determine the capabilities of the NFC chip.
Available recipes: createDocumentSession(mode:, masks:, oneShotKyc:) for photos, createVideoSession(mode:, masks:, twoSided:) for camera streams,, createFaceMatchingSession(), createLivenessSession() and createTextSession(mode:, masks:).
When you are done with a scan (or when leaving the result screen), call engine.closeSession() . The worker stays ready; the instance is not reloaded.
5. MRZ-reading – why it needs for NFC, example of result
The MRZ scan in the OCRStudio Flutter SDK exists to unlock the NFC chip: the chip’s access key is derived from the document number, date of birth and expiry date printed in the MRZ. Chip reading always begins with a camera scan.
Feed frames to the session and stop when the result is final. CameraImage from the camera plugin is converted by ImageData.fromCamera (planes are transferred without copying via TransferableTypedData); the worker applies the sensor rotation natively:
final frame = ImageData.fromCamera(cameraImage);
if (frame == null) return; // unsupported format
final res = await engine.processFrame(frame, numRotations);
if (res.isAllTargetsFinal && res.targets.isNotEmpty) {
final target = res.targets[0];
final docNumber =
PassportNfc.sanitiseDocNumber(target.stringValue('mrz_number') ?? '');
final dob = PassportNfc.parseDate(target.stringValue('mrz_birth_date'));
final expiry = PassportNfc.parseDate(target.stringValue('mrz_expiry_date'));
if (dob != null && expiry != null) {
await _stopScanning();
_startNfc(docNumber, dob, expiry);
}
}The description of the result could be as follows:
{
"target_type": "document",
"specific_type": "are.passport.type1",
"specific_type_has_rfid": 1,
"specific_type_display_name": "United Arab Emirates Passport",
"instruction_code": "none",
"item_types": [
"fraud_attempt",
"image",
"page",
"string",
"template"
],
"attributes": {}
}And the following fields can be obtained as a result of recognition:
mrz_number: AAAA14975
mrz_birth_date: 02.02.1974
mrz_expiry_date: 05.10.2016...6. NFC reading — how to read, example of result
In the OCRStudio Flutter SDK, PassportNfc.readPassport performs BAC (or PACE when the chip supports it), reads DG1 (MRZ) and DG2 (photo) and returns a PassportNfcResult:
final nfc = await PassportNfc.readPassport(
documentNumber: docNumber,
dateOfBirth: dob,
dateOfExpiry: expiry,
);Chip photos are often JPEG2000 — PassportNfc detects that and converts them to JPEG.
If !nfc.hasError && nfc.rawMrz != null, feed the chip data back into the same document session – engine.processNfc builds the doc_type + physical_fields map for you and answers with the updated result:
final updated = await engine.processNfc(
docType: target.description.specificType,
mrz: nfc.rawMrz!,
photoBase64: nfc.photoBase64,
);The chip fields now appear in updated.targets – the SDK cross-checks them against the OCRed data, which is the actual verification step. The sample keeps the document session open while the result screen is shown exactly for this.
7. Face matching (with selfie, with NFC-photo)
Face matching is a separate short-lived session — two images in, one similarity result out:
await engine.createFaceMatchingSession();
try {
await engine.processImage(selfie);
final result = await engine.processImage(docPhoto);
} finally {
await engine.closeSession();
}
final target = result.targets.first;
target.stringValue('face_similarity_status'); // Ok
target.stringValue('similarity_estimation'); // 0.999994For NFC-photo matching pass the chip photo instead: decode nfcResult.photoBase64 into Uint8List and processImage(bytes) it against the selfie. The document photo is also available as target.imageBase64(‘photo’) when the bundle extracts it.
8. Conclusion
By following the steps in this tutorial, developers can bring ID scanning, NFC chip reading, and face matching together in a single mobile KYC workflow for iOS and Android. These technologies help businesses automate identity verification, prevent fraud, and confirm that the passport belongs to the person presenting it.
With OCR Studio’s Zero-Trust approach, all these checks run directly on the user’s smartphone without transmitting sensitive identity data to external servers. This allows businesses to make customer onboarding faster and more convenient while maintaining full control over personal information and minimizing the risks associated with third-party services.