Giter VIP home page Giter VIP logo

mlkit_scanner's Introduction

MLKit Scanner

A Flutter plugin to detect barcodes, text, faces, and objects using Google MLKit API for iOS and Android

This Plugin uses Android CameraView library and iOS AVFoundation APIs for detecting objects from device's camera.

Note: This plugin is under development, and some APIs might not be available yet.

Features:

  • Display camera preview in a widget.
  • Set size of the camera preview.
  • Set overlay for camera preview.
  • Set area for detect object.
  • Pause/Resume camera preview.
  • Toogle device flash.
  • Set a preview scale
  • Use camera Zoom
  • Lock autofocus
Google MLKit APIs: Android iOS
Barcode scanning
------------------------ - -

Installation

First, add mlkit_scanner as a dependency in your pubspec.yaml.

iOS

iOS 11.0 of higher is needed to use the camera plugin.

Add key to the ios/Runner/Info.plist:

<key>NSCameraUsageDescription</key>
<string>...description...</string>

Android

Change the minimum Android sdk version to 21 (or higher) in your android/app/build.gradle file.

minSdkVersion 21

Example

import 'package:mlkit_scanner/mlkit_scanner.dart';

...

return SizedBox(
  height: 200.0                                 // CameraPreview needs height constraints, if you use widget 
                                                // in Column use SizedBox or Container with height.
  child: BarcodeScanner(
    cropOverlay: ScannerCropOverlay             // you can use default ScannerOverlay, create custom, or do not 
                                                // use it at all

    onScannerInitialized: _onScannerInitialized // callback with BarcodeScannerController for control camera 
                                                // and detection when camera preview initialize.
    
    onCameraInitializeError: (error) {          // Handling error if camera can't initialize on device.
      // handleError.
    }
    onScan: (barcode) {                         // Calls on success barcode recognition
      // Do anything with the code.
    },
  ),
);

Future<void> _onScannerInitialized(BarcodeScannerController controller) async {
    await controller.startScan(100)             // Detection starts only after this call.
                                                // 100 - delay in milliseconds between detection for decreasing 
                                                // CPU consumption. Detection happens every 100 milliseconds 
                                                // skipping frames during delay. Use 0 to turn off delay.

    await controller.stopScan()                 // You can stop detection.

    await controller.setDelay(200)              // Or set delay while detection is going.

    await controller.toggleFlash()              // Toggle device flash. Can throw an Exception if device 
                                                // doesn't have flash.

    await controller.pauseCamera()              // Pause camera preview, detection also stops.

    await controller.resumeCamera()             // Resume camera preview, detection resumes too if 
                                                // controller.startScan calls before.
                                                
    await controller.setZoom(0.5)               // Set camera zoom. Values must be in range 0...1                            
}

Contributing:

Contributions are welcome.

mlkit_scanner's People

Contributors

8symbols avatar skrjt avatar jagrdev avatar grebennikovlmax avatar shirne avatar

Stargazers

Namba Software avatar Laki Pirelly avatar Suyash Sharma avatar Artem avatar Hieu Luu avatar  avatar  avatar Evgeny avatar  avatar Sergey Brushkov avatar Jaeyong Kim avatar  avatar Neal Sanche avatar Daniil Ivanov avatar  avatar  avatar  avatar Dollarkillerx avatar Face The Flames avatar Andrey Gurev avatar devtimberg avatar Renat Fakhrutdinov avatar  avatar Vladimir Luzhin avatar

Watchers

 avatar

mlkit_scanner's Issues

Ability to Start Scan Without a Button(when page is loaded)

I don't know if it's possible, but i have tried in different ways and i didn't get a positive result. So if anyone knows, or can implement a way to start scaning when the page is loaded,(without a button) i would really appreciate it.

App failed to build : Type mismatch: inferred type is String? but String was expected

Hi, thank you for the library. I already follow the steps and refer to this repo for instructions. But when I try to run the app an error occurred :

e: /Users/me/FlutterProjects/flutter/.pub-cache/hosted/pub.dartlang.org/mlkit_scanner-0.3.1/android/src/main/kotlin/com/dns_technologies/mlkit_scanner/analyzer/MlSingleBarcodeAnalyzer.kt: (89, 28): Type mismatch: inferred type is String? but String was expected

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':mlkit_scanner:compileDebugKotlin'.

Compilation error. See log for more details

flutter -v doctor output :

[✓] Flutter (Channel stable, 3.0.5, on macOS 11.6.2 20G314 darwin-x64, locale en-MY)
• Flutter version 3.0.5 at /Users/me/FlutterProjects/flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision f1875d570e (3 weeks ago), 2022-07-13 11:24:16 -0700
• Engine revision e85ea0e79c
• Dart version 2.17.6
• DevTools version 2.12.2

[✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
• Android SDK at /...
• Platform android-32, build-tools 32.0.0
• ANDROID_HOME = /...
• Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• CocoaPods version 1.11.2

[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.2)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)

[✓] IntelliJ IDEA Community Edition (version 2018.2.6)
• IntelliJ at /Applications/IntelliJ IDEA CE.app
• Flutter plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.69.2)
• VS Code at ...
• Flutter extension version 3.46.0

[✓] HTTP Host Availability
• All required HTTP hosts are available

• No issues found!

mlkit_scanner package conflicts with google_mlkit_text_recognition package

Hi all,
thanks for the efforts in making this package.
I started working on the app which uses this scanner a month ago. this package was one of the first that I initialized and tested as a widget to make sure I can use it when I need it. I used the example you pointed out and Initialized the BarcodeScanner Widget accordingly. However, now when I got back to it to actually use it (or let's say join with the rest of the screens in the app) It just keeps crashing. First I taught it's the "clash" between google_ml_kit and mlkit_scanner packages, but now, as I ended up trying to init the page with mlkit_scanner directly as a child class of MyApp (main) widget:

In my main.dart file I did this

class MyApp extends StatelessWidget {
  const MyApp(
      {
      Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'testapp',
      theme: theme,
      home: const ScanQRCodePage(),
    );
  }
}

in scan QR code page I did this:

import 'package:flutter/material.dart';
import '../ui/helpers/animations_helper.dart';
import 'package:mlkit_scanner/mlkit_scanner.dart';
import './connect_bluetooth_page.dart';

class ScanQRCodePage extends StatefulWidget {

  const ScanQRCodePage({super.key});

  @override
  State<ScanQRCodePage> createState() => ScanQRCodePageState();
}

class ScanQRCodePageState extends State<ScanQRCodePage> {
  BarcodeScannerController? barcodeScannerController;
  String _imei = '';

  @override
  Widget build(BuildContext context) => Scaffold(
      appBar: AppBar(title: const Text('Scan QR Code')),
      body: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(24),
            child: Text('scan QR code page $_imei'),
          ),

          Expanded(
            flex: 10,
            child: BarcodeScanner(
                cropOverlay: const CropRect(scaleHeight: 0.2, scaleWidth: 0.3),
                onScannerInitialized: (cntr) => _onScannerInitialized(cntr),
                onScan: (code) {

                  if (code.length == 15) {
                    setState(() {
                      _imei = code;
                    });

                    barcodeScannerController?.cancelScan();

                    Navigator.push(
                      context,
                      CustomPageRoute(
                          builder: ConnectBluetoothPage(imei: _imei),
                          direction: AxisDirection.right),
                    );
                  }
                },
                onCameraInitializeError: (error) {
                  print('ERROR ON CAMERA ' + error.toString());
                }),
          )
        ],
      ));

  Future<void> _onScannerInitialized(
      BarcodeScannerController? controller) async {
    if (controller == null) {
      print('Controller is null, terminating');
      return;
    }
    setState(() {
       barcodeScannerController = controller;
    });
    await barcodeScannerController.startScan(100);
  }
}

This is the Debug log:

D/FlutterBluePlugin(30710): onAttachedToEngine
D/FlutterBluePlugin(30710): setup
D/FlutterBluePlugin(30710): onAttachedToActivity
Connecting to VM Service at ws://127.0.0.1:58232/iO3McQOZTTo=/ws
D/ForceDarkHelper(30710): updateByCheckExcludeList: pkg: com.example.fleetstep_connect_testapp activity: com.example.fleetstep_connect_testapp.MainActivity@14699b1
I/chatty  (30710): uid=10326(com.example.fleetstep_connect_testapp) identical 3 lines
D/ForceDarkHelper(30710): updateByCheckExcludeList: pkg: com.example.fleetstep_connect_testapp activity: com.example.fleetstep_connect_testapp.MainActivity@14699b1
W/Gralloc3(30710): mapper 3.x is not supported
D/ForceDarkHelper(30710): updateByCheckExcludeList: pkg: com.example.fleetstep_connect_testapp activity: com.example.fleetstep_connect_testapp.MainActivity@14699b1
W/Gralloc3(30710): allocator 3.x is not supported
E/libc    (30710): Access denied finding property "vendor.camera.hal1.packagelist"
W/CameraViewEngin(30710): type=1400 audit(0.0:8051): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=25852 scontext=u:r:untrusted_app:s0:c70,c257,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
I/connect_testap(30710): ProcessProfilingInfo new_methods=1619 is saved saved_to_disk=1 resolve_classes_delay=8000
D/ForceDarkHelper(30710): updateByCheckExcludeList: pkg: com.example.fleetstep_connect_testapp activity: com.example.fleetstep_connect_testapp.MainActivity@14699b1
I/chatty  (30710): uid=10326(com.example.fleetstep_connect_testapp) identical 3 lines
D/ForceDarkHelper(30710): updateByCheckExcludeList: pkg: com.example.fleetstep_connect_testapp activity: com.example.fleetstep_connect_testapp.MainActivity@14699b1
I/Process (30710): Sending signal. PID: 30710 SIG: 9

UPDATE: As I wanted to make sure that the issue truly exists I just copy-pasted the example to my project in order to see if it works. When I hit the startScan button the app just crashes. the only thing in debug log is this:
I/Process (12983): Sending signal. PID: 12983 SIG: 9
Lost connection to device.
Exited (sigterm)

UPDATE 2: I created a completely new project with mlkit_scanner and it worked. Got back to my project and commented out google_mlkit_text_recognition package and now it worked in my project also. This basically means: mlkit_scanner conflicts with google_mlkit_text_recognition. This is as far as I go, hope you find out what's the issue here. good luck.

Scan Text implementation

Hi,
im very interested in your dart package. I want to scan text (and picture to text) but only barcodes are been recognized.
Are you working on this functionality?
Best regards

Needs android namespace for Gradle 8 support

A problem occurred configuring project ':mlkit_scanner'.
[        ] > Could not create an instance of type com.android.build.api.variant.impl.LibraryVariantBuilderImpl.
[        ]    > Namespace not specified. Specify a namespace in the module's build file. See https://d.android.com/r/tools/upgrade-assistant/set-namespace for information about setting the namespace.

Should be compatible with the version of Gradle suggested by Android Studio.

Can not build Gradle

..../mlkit_scanner/analyzer/MlSingleBarcodeAnalyzer.kt: (90, 32): Smart cast to 'String' is impossible, because 'it.message' is a property that has open or custom getter

../mlkit_scanner-0.3.2/android/src/main/kotlin/com/dns_technologies/mlkit_scanner/CenterFocusView.kt: (134, 45): Type mismatch: inferred type is MotionEvent? but MotionEvent was expected

.../mlkit_scanner-0.3.2/android/src/main/kotlin/com/dns_technologies/mlkit_scanner/CenterFocusView.kt: (62, 13): 'onLongPress' overrides nothing

.../mlkit_scanner-0.3.2/android/src/main/kotlin/com/dns_technologies/mlkit_scanner/CenterFocusView.kt: (57, 13): 'onSingleTapUp' overrides nothing

When I build , I got above issues.

Crash when scanning barcode / qrcode (android)

Hello again. This happen when I try to integrate the lib into my own project. Running the example project does not produce this error.

java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/mlkit/vision/barcode/Barcode;
    at com.dns_technologies.mlkit_scanner.analyzer.MlSingleBarcodeAnalyzer.onSuccessScan(MlSingleBarcodeAnalyzer.kt:102)
    at com.dns_technologies.mlkit_scanner.analyzer.MlSingleBarcodeAnalyzer.$r8$lambda$Y-tNOhaaHvcyOtTUkuHQ-dP33cw(MlSingleBarcodeAnalyzer.kt)
    at com.dns_technologies.mlkit_scanner.analyzer.MlSingleBarcodeAnalyzer$$ExternalSyntheticLambda2.onSuccess(D8$$SyntheticClass)
    at com.google.android.gms.tasks.zzm.run(com.google.android.gms:play-services-tasks@@18.0.1:1)
    at android.os.Handler.handleCallback(Handler.java:836)
    at android.os.Handler.dispatchMessage(Handler.java:103)
    at android.os.Looper.loop(Looper.java:203)
    at android.app.ActivityThread.main(ActivityThread.java:6410)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1084)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:945)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.mlkit.vision.barcode.Barcode" on path: DexPathList[[zip file "/data/app/my.app.nex-2/base.apk"],nativeLibraryDirectories=[/data/app/my.app.nex-2/lib/arm64, /data/app/my.app.nex-2/base.apk!/lib/arm64-v8a, /system/lib64, /vendor/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at com.dns_technologies.mlkit_scanner.analyzer.MlSingleBarcodeAnalyzer.onSuccessScan(MlSingleBarcodeAnalyzer.kt:102) 
    at com.dns_technologies.mlkit_scanner.analyzer.MlSingleBarcodeAnalyzer.$r8$lambda$Y-tNOhaaHvcyOtTUkuHQ-dP33cw(MlSingleBarcodeAnalyzer.kt) 
    at com.dns_technologies.mlkit_scanner.analyzer.MlSingleBarcodeAnalyzer$$ExternalSyntheticLambda2.onSuccess(D8$$SyntheticClass) 
    at com.google.android.gms.tasks.zzm.run(com.google.android.gms:play-services-tasks@@18.0.1:1) 
    at android.os.Handler.handleCallback(Handler.java:836) 
    at android.os.Handler.dispatchMessage(Handler.java:103) 
    at android.os.Looper.loop(Looper.java:203) 
    at android.app.ActivityThread.main(ActivityThread.java:6410) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1084) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:945) 

displayValue

google_mlkit_barcode_scanning returns both the rawValue and the displayValue, but what comes in here is just the rawValue.
It would be useful to have both or the entire Barcode object with all the related information

Platform Exception

First of all, I would like to thank you for your doing this plugin.
I am problem a bite when I run on Physical Device iOS.
I faced like the following image. Could I need to do anything for this?
Screen Shot 2022-09-16 at 9 35 41 AM

CameraViewFactory.kt

.../Flutter SDK/flutter_3.0.0/.pub-cache/hosted/pub.dartlang.org/mlkit_scanner-0.2.0/android/src/main/kotlin/com/dns_technologies/mlkit_scanner/CameraViewFactory.kt: (14, 5): 'create' overrides nothing

For iOS working fine but For android it given above error.
Thanks in advance

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.