lutter 调用原生硬件 Api 实现扫码
一、Flutter 扫描二维码条形码插件 barcode_scan
1. 安装
// 请按照官方文档或相关教程进行安装
2. 配置权限
// 在你的 AndroidManifest.xml 中添加摄像头权限 Add the camera permission to your AndroidManifest.xml // 在你的 AndroidManifest.xml 中添加 BarcodeScanner 活动。请不要修改它的名称。 Add the BarcodeScanner activity to your AndroidManifest.xml. Do NOT modify the name.
3. 检查并配置 build.gradle
dependencies: barcode_scan: ^1.0.0 <activity android:name="com.apptreesoftware.barcodescan.BarcodeScannerActivity"/>
3.1 编辑位于 android 目录下的 build.gradle
// 注意:官方文档配置的 kotlin_version 的版本是1.2.31,但实际上1.2.31会报错。所以本项目使用1.3.0。 buildscript { ext.kotlin_version = '1.3.0' ... dependencies { ... classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } }
3.2 编辑位于 android/app 目录下的 build.gradle
apply plugin: 'kotlin-android' ... dependencies { ... implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" }
4. 使用插件
import 'package:flutter/material.dart'; import 'package:barcode_scan/barcode_scan.dart'; import 'package:flutter/services.dart'; class ScanPage extends StatefulWidget { ScanPage({Key key}) : super(key: key); _ScanPageState createState() => _ScanPageState(); } class _ScanPageState extends State<ScanPage> { var barcode; Future _scan() async { try { String barcode = await BarcodeScanner.scan(); setState(() { return this.barcode = barcode; }); } on PlatformException catch (e) { if (e.code == BarcodeScanner.CameraAccessDenied) { setState(() { return this.barcode = 'The user did not grant the camera permission!'; }); } else { setState(() { return this.barcode = 'Unknown error: $e'; }); } } on FormatException { setState(() => this.barcode = 'null (User returned using the "back"-button before scanning anything. Result)'); } catch (e) { setState(() => this.barcode = 'Unknown error: $e'); } } @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton( child: Icon(Icons.camera_roll), onPressed: _scan, ), appBar: AppBar( title: Text("扫码"), ), body: Text("扫码--${barcode}"), ); } }
二、Flutter 使用 barcode_scan 提示的错误解决方案
// 错误描述: Android dependency ‘androidx.core:core’ has different version for the compile (1.0.0) and runtime (1.0.2) classpath. You should manually set the same version via DependencyResolution 解决办法 1.android/gradle/wrapper/gradle-wrapper.properties里面 distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip 2.android/build.gradle dependencies { classpath 'com.android.tools.build:gradle:3.3.0' } 3.android/gradle.properties 加入 android.enableJetifier=true android.useAndroidX=true 4.android/app/build.gradle 修改版本号: make sure compileSdkVersion and targetSdkVersion are at least 28. testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 5.android/app/build.gradle /defaultConfig加上 multiDexEnabled true