我们使用到的第三方插件为barcode_scan2
地址为:https://pub.flutter-io.cn/packages/barcode_scan2
准备工作
安卓使用此插件需要注意以下几点:
- 相机权限添加
将相机权限添加到您的 AndroidManifest 中.xml
<uses-permission android:name="android.permission.CAMERA" />
- 这个插件是用 Kotlin 编写的。因此,您需要向项目添加 Kotlin 支持。
编辑项目级 build.gradle 文件,使其如下所示:
buildscript {
ext.kotlin_version = '1.3.61'
// ...
dependencies {
// ...
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
// ...
编辑您的应用级 build.gradle 文件,使其如下所示:
apply plugin: 'kotlin-android'
// ...
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
// ...
}
- minSdkVersion 18 以上
使用
import 'package:flutter/material.dart';
import 'package:barcode_scan2/barcode_scan2.dart';
class BarcodeScanPage extends StatefulWidget {
BarcodeScanPage({
Key? key}) : super(key: key);
@override
State<BarcodeScanPage> createState() => _BarcodeScanPageState();
}
class _BarcodeScanPageState extends State<BarcodeScanPage> {
//调用相机扫描条形码二维码的方法
void _doBarcodeScan() async {
var options = const ScanOptions(
//是否自动打开闪光灯
autoEnableFlash: true,
strings: {
'cancel':'取消',
'flash_on':'打开flash',
'flash_off':'关闭flash'
}
);
var result = await BarcodeScanner.scan(options: options);
print(result.type);
print(result.rawContent);
print(result.format);
print(result.formatNote);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("扫码演示"),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _doBarcodeScan,
child: Text("扫码条形码 二维码"),
)
],
),
);
}
}
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({
Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: BarcodeScanPage(),
);
}
}