Flutter - 生成二维码与识别二维码

18,069 阅读1分钟

#生成二维码

##首先需要在pubspec.yaml:中添加

qr_flutter: ^1.1.3

其次,引入代码:

import 'package:qr_flutter/qr_flutter.dart';

核心代码如下:

        child: QrImage(
          data: "这里是需要生成二维码的数据",
          size: 100.0,
          onError: (ex) {
            print("[QR] ERROR - $ex");
          },

整体代码与效果如下:

#识别二维码

这里也用第三方的包在pubspec.yaml中添加库链接

barcode_scan: ^0.0.4

识别的主要代码如下:

  Future scan() async {
    try {
      String barcode = await BarcodeScanner.scan();
      setState(() {
        return this.barcode = barcode;
      });
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        setState(() {
          return this.barcode = 'The user did not grant the camera permission!';
        });
      } else {
        setState(() {
          return 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');
    }
  }

整体代码如下:

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

class scanqr extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: sacnBody(),
    );
  }
}

class sacnBody extends StatefulWidget {
@override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _MyScanState();
  }
}

class _MyScanState extends State<sacnBody> {
  String barcode = "";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: new AppBar(
        title: new Text('QR Code'),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 15.0,vertical: 8.0),
              child: RaisedButton(
                  color: Colors.orange,
                  textColor: Colors.white,
                  splashColor: Colors.blueGrey,
                  onPressed: scan,
                  child: const Text('START CAMERA SCAN')

              ),
            ),
            Padding (
              padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
              child: Text(barcode, textAlign: TextAlign.center,),
            )
          ],
        ),
      ),
    );
  }


  Future scan() async {
    try {
      String barcode = await BarcodeScanner.scan();
      setState(() {
        return this.barcode = barcode;
      });
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        setState(() {
          return this.barcode = 'The user did not grant the camera permission!';
        });
      } else {
        setState(() {
          return 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');
    }
  }


}

安卓和iOS工程设置如下:

Android For Android, you must do the following before you can use the plugin:

Add the camera permission to your AndroidManifest.xml

<uses-permission android:name="android.permission.CAMERA" />

Add the Barcode activity to your AndroidManifest.xml

<activity android:name="com.apptreesoftware.barcodescan.BarcodeScannerActivity"/>

iOS To use on iOS, you must add the the camera usage description to your Info.plist

<key>NSCameraUsageDescription</key>
<string>Camera permission is required for barcode scanning.</string>