Flutter:如何暂停和重新启动“Stream”侦听器?

4

我正在开发一个用于读取二维码的Flutter应用程序,使用的是qr_code_scanner:^0.3.5库。下面是我的代码:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';

class ScanQRCodeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Text("Scan QR Code"),
        ),
        body: _ScanQRCodeUI());
  }
}

class _ScanQRCodeUI extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ScanQRCodeUIState();
  }
}

class _ScanQRCodeUIState extends State<_ScanQRCodeUI> {
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  Barcode result;
  QRViewController controller;

  // In order to get hot reload to work we need to pause the camera if the platform
  // is android, or resume the camera if the platform is iOS.
  @override
  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller.pauseCamera();
    } else if (Platform.isIOS) {
      controller.resumeCamera();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(flex: 4, child: _buildQrView(context)),
        Expanded(flex: 1, child: _dataDisplayUI())
      ],
    );
  }

  Widget _buildQrView(BuildContext context) {
    // For this example we check how width or tall the device is and change the scanArea and overlay accordingly.
    var scanArea = (MediaQuery.of(context).size.width < 400 ||
            MediaQuery.of(context).size.height < 400)
        ? 200.0
        : 400.0;
    // To ensure the Scanner view is properly sizes after rotation
    // we need to listen for Flutter SizeChanged notification and update controller
    return QRView(
      key: qrKey,
      onQRViewCreated: _onQRViewCreated,
      overlay: QrScannerOverlayShape(
          borderColor: Colors.red,
          borderRadius: 10,
          borderLength: 30,
          borderWidth: 10,
          cutOutSize: scanArea),
    );
  }

  void _onQRViewCreated(QRViewController controller) {
    setState(() {
      this.controller = controller;
    });

    controller.scannedDataStream.listen((scanData) async {
      print("Hello0");
      setState(() {
        result = scanData;
        print(result.code);
      });

      // await controller.pauseCamera();
    });
  }

  Widget _dataDisplayUI() {
    const yellowColor = const Color(0xffEDE132);

    return Column(
      children: [
        Row(
          children: [
            Expanded(
                flex: 7,
                child: Container(
                  margin:
                      EdgeInsets.only(top: 30, bottom: 30, left: 10, right: 10),
                  child:
                      Text("You have added 12 products. Click here to publish.",
                          style: GoogleFonts.poppins(
                              textStyle: TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.normal,
                            fontSize: 14,
                          ))),
                )),
            Expanded(
                flex: 3,
                child: Container(
                  width: 60,
                  height: 60,
                  child: Center(
                      child: Text("12",
                          style: GoogleFonts.poppins(
                              textStyle: TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.bold,
                            fontSize: 21,
                          )))),
                  decoration:
                      BoxDecoration(shape: BoxShape.circle, color: yellowColor),
                ))
          ],
        )
      ],
    );
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }
}

我正在使用这个应用程序逐个扫描产品,就像收银员在超市使用条形码扫描仪一样。

问题是,这个扫描器正在监听一个 stream 并且一直在运行。请注意 _onQRViewCreated 方法。结果是,在我们将相机移动到下一个 QR 代码之前,同一个 QR 代码被多次读取。

我该如何确保两次扫描之间有延迟?例如,当我扫描 QR 代码时,我必须等待另外 2 秒钟才能扫描下一个 QR。

如果我创建两次扫描之间的延迟的想法是错误的,我也可以接受其他想法。

2个回答

1

您可以使用

controller.scannedDataStream.first

停止从流中监听其他事件的解决方案。

另一个解决方案是设置一个内部状态属性,如下所示:

bool QrBeingProcessed = false;

当你扫描第一个二维码时,将其设置为true,直到完成。


1
另一种方法是使用DateTime来检查当前扫描和上一次扫描之间的时间差是否小于指定的时间(比如3秒)。如果是,则不将状态设置为新的扫描数据。实际上,这样可以在每个二维码扫描之间设置一个3秒的延迟。请参见下面的代码。
     controller.scannedDataStream.listen((scanData) {
      final currentScan = DateTime.now();
      if (lastScan == null || currentScan.difference(lastScan!) > const Duration(seconds: 3)) 
      {
        lastScan = currentScan;
        print(scanData.code);
  
        setState(() {
          result = scanData;
          print('the qr just read was ' + scanData.code);
        });
     }
  });

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接