效果图:
第一步:
导入第三方库:barcode_scan
第二步:
<uses-permission android:name="android.permission.CAMERA" />
第三步:
3.1 的 编 辑 你 的 d android 的 目 录 下 面 的 e build.gradle ( Edit your project-level
build.gradle file to look like this)
注意: : 官方文档配置的 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"
}
}
第四步:编辑你 的 p android/app 的 目 录下 面 的 e build.gradle ( Edit your app-levelbuild.gradle file to look like this)
apply plugin: 'kotlin-android'
...
dependencies {
implementation
"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
...
}
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> {
String 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.photo_camera),
onPressed: _scan,
),
appBar: AppBar(
title: Text("扫码"),
),
body: Text("${barcode}")
);
}
}