Scan barcodes in Jetpack Compose using ML Kit and CameraX
4 min readNov 20, 2023
Hey y’all, grab a cup of coffee ☕, and let’s see how to implement a barcode scanner in Jetpack Compose.
Dependencies
Open :app/build.gradle.kts
and add the ML Kit, CameraX, and the Accompanist dependencies.
dependencies {
// ML Kit
implementation("com.google.mlkit:barcode-scanning:17.2.0")
// CameraX
val cameraxVersion = "1.4.0-alpha02"
implementation("androidx.camera:camera-camera2:$cameraxVersion")
implementation("androidx.camera:camera-lifecycle:$cameraxVersion")
implementation("androidx.camera:camera-view:$cameraxVersion")
// Permissions
implementation("com.google.accompanist:accompanist-permissions:0.33.2-alpha")
}
Now go to AndroidManifest.xml
and add this inside the application.
<meta-data
android:name="com.google.mlkit.vision.DEPENDENCIES"
android:value="barcode" />
I do like to keep the camera and its functions in a separate class called BarcodeCamera
. Now let’s create the camera preview which is a Composable
. This will have a callback that will return the scanned barcode.
class EanCamera {
private var camera: Camera? = null
@Composable
fun CameraPreview(
onBarcodeScanned: (Barcode?) -> Unit
) {
//…