问题描述
如何在没有相机用户界面的情况下使用颤振扫描二维条码?我不需要查看相机预览。我只想点击“扫描”按钮,相机开始寻找条形码,但它没有显示手机相机在 UI 中看到的内容。
解决方法
您可以考虑使用 qr_code_scanner 包 (pub link)。它不是在新视图中打开,而是使用自定义视图进行预览。然后,您可以操纵视图的尺寸以满足您的需要。请注意,使用 Visibility
或通过为其父级大小设置 0 使其不可见将禁用相机。给它(例如)1 像素的高度仍然有效。
示例代码(使用 0.4.0
包的 qr_code_scanner
版运行)
import 'package:flutter/material.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',theme: ThemeData(
primarySwatch: Colors.blue,),home: MyHomePage(title: 'QR scanner demo'),);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key,this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String result = '';
QRViewController controller;
bool isVisible = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
Container(
width: 200,// 1 pixel,as a height 0 disables the view
height: isVisible ? 100 : 1,child: QRView(
key: GlobalKey(),onQRViewCreated: _onQRViewCreated,Text(
'The barcode value was:',Text(
'$result',style: Theme.of(context).textTheme.headline4,],floatingActionButton: FloatingActionButton(
child: Icon(Icons.visibility),onPressed: () {
setState(() {
isVisible = !isVisible;
});
},);
}
void _onQRViewCreated(QRViewController controller) {
this.controller = controller;
controller.scannedDataStream.listen((scanData) {
setState(() {
result = scanData.code;
});
});
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
}
我发现一种解决方案是将 QRView
放在堆栈中,s.t.它隐藏在另一个视图下