A demo project showcasing Barcode Scanning implementation in Compose Multiplatform (CMP), targeting both Android and iOS. This project serves as a practical example for the technical article Barcode Scanning in Compose Multiplatform.
- Cross-Platform UI: Built with Compose Multiplatform for a consistent look and feel.
- Native Performance: Leverages platform-specific APIs for camera and barcode processing.
- Real-time Detection: Fast and accurate scanning of various barcode formats (QR, EAN, etc.).
- Shared Logic: Centralized state management and scanning callbacks.
- Compose Multiplatform: Shared UI framework.
- Kotlin Multiplatform: Shared business logic.
- Android:
- CameraX: Modern Android camera library.
- ML Kit Barcode Scanning: High-performance barcode detection.
- iOS:
- AVFoundation: Native Apple framework for camera and metadata capture.
:shared: Contains the shared Compose UI and theexpect/actualdeclarations for the barcode scanner.commonMain: Shared UI and scanner interface.androidMain: Implementation using CameraX and ML Kit.iosMain: Implementation using AVFoundation andUIKitView.
:androidApp: Entry point for the Android application.iosApp: Xcode project for the iOS application.
- Android Studio (latest version)
- Xcode (for iOS development)
- Kotlin Multiplatform Mobile plugin installed in Android Studio.
- Clone the repository:
git clone https://github.com/your-username/BarcodeScanningCMP.git
- Open the project in Android Studio.
- Select
androidAppin the run configurations and click Run. - Or use the command line:
./gradlew :androidApp:assembleDebug
- Open
iosApp/iosApp.xcworkspacein Xcode. - Select your target device/simulator and click Run.
- Note: Camera features require a physical device for actual scanning.
This project highlights a powerful pattern in Compose Multiplatform: declaring @Composable functions as expect/actual. This allows you to define a UI component's interface in common code while providing platform-specific implementations that leverage native views:
- Android: Uses
AndroidViewto host a CameraXPreviewView, with anImageAnalysisanalyzer that passes frames to ML Kit. - iOS: Uses
UIKitViewto host a customUIView(BarcodeScannerView) that manages anAVCaptureSessionand handlesAVCaptureMetadataOutput.
This approach demonstrates that the expect/actual mechanism isn't limited to logic—it's equally effective for platform-integrated UI components.
This project was created as a demo for the article Barcode Scanning in Compose Multiplatform on KMP Bits. Feel free to use it as a reference for your own Compose Multiplatform projects!