本文由动哒公众号(dongda_5g),QQ群(174353204)提供,欢迎关注获取技术支持,有任何问题群里都会回复。
二维码扫描是现在APP的一个普遍的需求,几乎所有的APP都有这一项功能,本文来探讨下在flutter的项目中,如何实现二维码扫描,以及结果的跳转。
我这里使用的是barcode_scan 这个插件。在开始之前,我要说明下,我这个例子运行的flutter版本是1.12或者1.17,请注意!
- 在项目文件pubspec.yaml中引入barcode_scan 插件,我这里使用的是3.0.0的版本
barcode_scan: ^3.0.0
2.修改AndroidManifest.xml文件,添加相机权限,
<uses-permission android:name="android.permission.CAMERA"/>
官方的说明还有添加kotlin的依赖,不过,创建flutter项目的时候,自然有kotlin的依赖。
对于3.0.0版本的插件,app/build.gradle,需要修改下minSdkVersion的版本改为18。
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.barcode_scan_demo"
minSdkVersion 18
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
3.完整的例子:
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/material.dart';
class BarCodeScanPage extends StatefulWidget {
BarCodeScanPage({Key key}) : super(key: key);
@override
_BarCodeScanPageState createState() => _BarCodeScanPageState();
}
class _BarCodeScanPageState extends State<BarCodeScanPage> {
String content = '';
scan() async {
var options = ScanOptions();
ScanResult result = await BarcodeScanner.scan(options: options);
print(result.rawContent);
setState(() {
content = result.rawContent;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BarCodeScanDemo'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.camera_alt),
onPressed: () {
scan();
},
),
],
),
body: Center(
child: Text('识别二维码结果:$content'),
),
);
}
}
效果如下:
github地址:https://github.com/jishaofeng89/barcode_scan_demo
b站视频教程地址:https://www.bilibili.com/video/BV1cK411L7My