无法使用条形码扫描仪显示条形码的内容

时间:2020-07-17 13:07:48

标签: flutter dart barcode-scanner

我一直在尝试使用条形码扫描仪显示商品的条形码... 我已经编写了用于扫描条形码的代码,但由于显示错误而无法显示。 该代码能够首先打开相机,然后扫描条形码,直到在这里完全可以正常工作,但是当我尝试显示条形码时,它将引发异常。

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/services.dart';


class CartItems extends StatefulWidget {
  @override
  _CartItemsState createState() => _CartItemsState();
}

class _CartItemsState extends State<CartItems> {

  String barcode = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(child: Text('Code: ' + barcode)),
      floatingActionButton: FloatingActionButton(
        onPressed: barcodeScanning,
        child: Icon(Icons.add),
      ),
    );
  }

  Future barcodeScanning() async {
    try {
      String barcode = BarcodeScanner.scan() as String;
      setState(() => this.barcode = barcode);
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.cameraAccessDenied) {
        setState(() {
          this.barcode = 'No camera permission!';
        });
      } else {
        setState(() => this.barcode = 'Unknown error: $e');
      }
    } on FormatException {
      setState(() =>
      this.barcode =
      'Nothing captured.');
    } catch (e) {
      setState(() => this.barcode = 'Unknown error: $e');
    }
  }
}

请调查我正在努力解决此错误的问题。

1 个答案:

答案 0 :(得分:1)

传递扫描仪功能返回的结果。这样,函数执行并将其发现结果馈送到主上下文中,还添加了print()以在底部查看结果,以查看控制台中可能出现的异常

class CartItems extends StatefulWidget {
  @override
  _CartItemsState createState() => _CartItemsState();
}

class _CartItemsState extends State<CartItems> {

  String barcodeResult = "";
  String barcode = "";


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(child: Text('Code: ' + barcode)),
      floatingActionButton: FloatingActionButton(
        onPressed:(){ barcodeScanning().then((value) 
       {
          setState(()
           {barcodeResult = value;})})}// this should work
        child: Icon(Icons.add),
      ),
    );
  }

  Future barcodeScanning() async {
    try {
      String barcode = BarcodeScanner.scan() as String;
      setState(() => this.barcode = barcode);
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.cameraAccessDenied) {
        setState(() {
          this.barcode = 'No camera permission!';
        });
      } else {
        setState(() => this.barcode = 'Unknown error: $e');
      }
    } on FormatException {
      setState(() =>
      this.barcode =
      'Nothing captured.');
    } catch (e) {
      setState(() => this.barcode = 'Unknown error: $e');
    }
   return barcode;//this
  }
}