Flutter 调用摄像头扫描二维码插件

原生平台如果想要实现二维码扫描很简单,例如iOS可以根据Version库或者AVFoudation库很快定制出相应工具来,Flutter只能依赖第三方插件了。

插件依赖:

dependencies:
  flutter:
    sdk: flutter

  ...
  barcode_scan2: ^4.2.1

可以根据自己的Flutter项目选择是1代还是2代。1代不支持空安全,二代支持。
另外不要忘记了该插件最低依赖为 Android v 18,低于该平台将无法编译。

原生项目权限:

以Android为例,在Mainifexist.xml中声明一下权限:
(uses-permission标签)

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.today_art">

   <application
   ...
   </application>

   <uses-permission android:name="android.permission.CAMERA" />
    
</manifest>

调用

此操作是个异步任务。

ScanOptions是个界面配置模型,配置返回键文字,闪光灯开启与关闭状态的文字。result是异步返回结果。

  _openQREvent() async {
    
    
    var options = const ScanOptions(
        android: AndroidOptions(aspectTolerance: 0.5, useAutoFocus: true),
        autoEnableFlash: false,
        strings: {
    
    'cancel': '退出', 'flash_on': '开启闪光灯', 'flash_off': '关闭闪光灯'}
    );
    var result = await BarcodeScanner.scan(options: options);
    String qrcode = result.rawContent;
    print(qrcode);
    print(result.type); // The result type (barcode, cancelled, failed)
    print(result.rawContent); // The barcode content
    print(result.format); // The barcode format (as enum)
    print(result.formatNote); //
  }

界面如下:
请添加图片描述

猜你喜欢

转载自blog.csdn.net/kicinio/article/details/130022338