本文实例为大家分享了Flutter实现扫二维码功能的具体代码,供大家参考,具体内容如下
首先在pubspec.yaml中添加:
dependencies:
qrscan: ^0.3.2
event_bus: ^2.0.0
在androd清单文件中加入以下权限:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<!--
路径:E:\chen\android\app\src\main\AndroidManifest.xml
-->
import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;
import 'package:event_bus/event_bus.dart';
void main() {
runApp(MyApp());
}
final eventBus = EventBus();
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: HomePage());
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("QRScan")),
body: BodyContent(),
);
}
}
class BodyContent extends StatelessWidget {
const BodyContent({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [HYButton(), HYText()],
));
}
}
class HYButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ElevatedButton(
child: Text("扫一扫"),
onPressed: scan,
);
}
Future scan() async {
String? cameraScanResult = await scanner.scan(); //通过扫码获取二维码中的数据
final info = QRInfo("${cameraScanResult}");
eventBus.fire(info);
print(cameraScanResult); //在控制台打印
}
}
class HYText extends StatefulWidget {
@override
_HYTextState createState() => _HYTextState();
}
class _HYTextState extends State<HYText> {
String message = "Hello GalenWu";
@override
void initState() {
super.initState();
eventBus.on<QRInfo>().listen((data) {
setState(() {
message = "${data.qrcode}";
});
});
}
@override
Widget build(BuildContext context) {
return Text(
message,
style: TextStyle(fontSize: 30),
);
}
}
class QRInfo {
String? qrcode;
QRInfo(this.qrcode);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。