Flutter 应用实现条形码、二维码的扫描与生成

一、前言

我们开发原生的时候可以使用zxing进行生成条形码与二维码,但是flutter的插件中只找到了二维码的生成与扫描,业务需求里面需要条形码的生成,需要在原有的基础上进行修改。

二、效果图

image

image

三、扫码逻辑

通过MethodChannel调用原生代码,进行效果的实现

const MethodChannel _channel = const MethodChannel(‘qr_scan’)

四、具体实现方案

1.使用的第三方库

qrscan: ^0.2.17

2.主要代码


class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String barcode = null;
  Uint8List bytes = Uint8List(0);
  @override
  initState() {

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('二维码生成器'),
        ),
        body: Container(
          margin: EdgeInsets.only(top: 50),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Container(
                  width: 200,
                  height: 200,
                  child: Image.memory(bytes),
                ),
//              _createBody(),
                Text(barcode ?? "请扫描相关的条形码"),
                MaterialButton(
                  onPressed: scan,
                  child: Text("Scan"),
                  color: Colors.blue,
                  textColor: Colors.white,
                ),
                MaterialButton(
                  onPressed: () => _generateBarCode(barcode),
                  child: Text("生成普通二维码"),
                  color: Colors.blue,
                  textColor: Colors.white,
                ),
                MaterialButton(
                  onPressed: () => _generateBarCode1(barcode),
                  child: Text("生成条形码"),
                  color: Colors.blue,
                  textColor: Colors.white,
                ),
              ],
            ),
          )
        ),
    );
  }

  ///扫描二维码
  Future scan() async {
    try {
      String barcode = await scanner.scan();
      print("这是扫描出来的结果"+barcode);
      setState(() {
        this.barcode = barcode;
        bytes=Uint8List(0);
//        ClipboardData data = new ClipboardData(text:barcode);
//        Clipboard.setData(data);
      });
    } on Exception catch (e) {
      if (e == scanner.CameraAccessDenied) {
        setState(() {
          this.barcode = 'The user did not grant the camera permission!';
        });
      } else {
        setState(() => this.barcode = 'Unknown error: $e');
      }
    } on FormatException {
      setState(() => this.barcode =
          'null (User returned using the "back"-button before scanning anything. Result)');
    } catch (e) {
      setState(() => this.barcode = 'Unknown error: $e');
    }
  }


  Future _generateBarCode(String inputCode) async {
    Uint8List result = await scanner.generateBarCode(inputCode);
    this.setState(() => this.bytes = result);
  }

  Future _generateBarCode1(String inputCode) async {
    Uint8List result = await scanner.generateBarCode1(inputCode);
    this.setState(() => this.bytes = result);
  }
}

五、注意事项

通过以上操作只能实现扫描与生成二维码的操作,条形码的生成还需要以下步骤进行修改。

1.flutter端添加关键代码

image


Future<Uint8List> generateBarCode1(String code) async {
  assert(code != null && code.isNotEmpty);
  return await _channel.invokeMethod('generate_barcode1', {"code": code});
}

2.Android端添加关键代码

image

case "generate_barcode1":
                this.result = result;
                generateQrCode1(call);
                break;

    private void generateQrCode1(MethodCall call) {
        String code = call.argument("code");
        Bitmap bitmap = createImage1(code, 200, 200, null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] datas = baos.toByteArray();
        this.result.success(datas);
    }


public static Bitmap createImage1(String text, int w, int h, Bitmap logo) {
        if (TextUtils.isEmpty(text)) {
            return null;
        }
        try {
            //条形码CODE_128
            BarcodeFormat fomt=BarcodeFormat.CODE_128;
            BitMatrix matrix=new MultiFormatWriter().encode(text, fomt, w, h);
            int width=matrix.getWidth();
            int height=matrix.getHeight();
            int[] pixel=new int[width*height];
            for(int i=0;i<height;i++){
                for(int j=0;j<width;j++){
                    if (matrix.get(j, i)) {
                        pixel[i * width + j] = 0xff000000;
                    } else {
                        pixel[i * width + j] = 0xffffffff;
                    }
                }
            }
            Bitmap bmapp=Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
            bmapp.setPixels(pixel, 0, width, 0, 0, width, height);
            return bmapp;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

3.二维码生成添加logo的方法

Bitmap imageBitmap = BitmapFactory.decodeFile("/sdcard/logo.png");

图片的路径需要保持一致, decodeFile默认的是sd卡

最后附上Demo地址,如有什么不足和错误请指正,觉得受用反手就给颗🌟吧

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在 Flutter 应用程序中实现二维码扫描,可以使用 `qr_code_scanner` 或 `barcode_scan` 插件。 `qr_code_scanner` 插件提供了一个 `QRView` widget,可以轻松地将二维码扫描器集成到应用程序中。以下是一个简单的示例: 1. 添加 `qr_code_scanner` 插件到 `pubspec.yaml` 文件中: ``` dependencies: qr_code_scanner: ^0.4.3 ``` 2. 导入 `qr_code_scanner` 包: ``` import 'package:qr_code_scanner/qr_code_scanner.dart'; ``` 3. 创建一个 `QRViewController` 和一个 `QRView`: ``` QRViewController controller; final GlobalKey qrKey = GlobalKey(debugLabel: 'QR'); @override Widget build(BuildContext context) { return QRView( key: qrKey, onQRViewCreated: _onQRViewCreated, ); } void _onQRViewCreated(QRViewController controller) { this.controller = controller; controller.scannedDataStream.listen((scanData) { // 处理扫描到的二维码 }); } ``` 当用户扫描二维码时,`QRViewController` 会不断发送扫描数据到 `scannedDataStream`,可以在监听函数中处理这些数据。 如果想要更多的控制权,可以使用 `barcode_scan` 插件。这个插件提供了一个 `scan()` 方法,可以启动一个新的扫描器界面,并且可以自定义扫描器的外观和行为。以下是一个简单的示例: 1. 添加 `barcode_scan` 插件到 `pubspec.yaml` 文件中: ``` dependencies: barcode_scan: ^2.0.0 ``` 2. 导入 `barcode_scan` 包: ``` import 'package:barcode_scan/barcode_scan.dart'; ``` 3. 调用 `scan()` 方法并处理返回的数据: ``` Future<void> scan() async { String barcode = await BarcodeScanner.scan(); // 处理扫描到的二维码 } ``` 在调用 `scan()` 方法时,会启动一个新的扫描器界面,并等待用户扫描二维码。当用户扫描二维码后,会返回扫描到的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值