本文实例为大家分享了Flutter实现扫二维码功能的具体代码,供大家参考,具体内容如下 首先在pubspec.yaml中添加: dependencies: qrscan: ^0.
本文实例为大家分享了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);
}
--结束END--
本文标题: Flutter实现扫二维码功能
本文链接: https://lsjlt.com/news/143531.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-21
2023-10-28
2023-10-28
2023-10-27
2023-10-27
2023-10-27
2023-10-27
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0