Flutter 掃碼

項目要求使用flutter實現(xiàn)掃碼能力,不想自己封裝插件能力简僧,于是我們找到了一些使用率較高三方庫兰绣,如下:

  • flutter_qr_reader 1.0.3(只支持二維碼,不支持條形碼聋丝,支持本地圖片) 1.0.5(要求flutter2.0以上索烹,支持空安全)
  • qr_code_scanner 0.3.5 (不支持文件【相冊】)
  • flutter_barcode_scanner (需要google服務)
根據(jù)項目情況,我們選擇使用 qr_code_scanner 弱睦。

首先百姓,pubspec.yaml 中添加:

qr_code_scanner: ^0.3.5

下一步,封裝我們的UI層每篷,創(chuàng)建 scan_code_page.dart 文件:

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

class ScanCodePage extends StatefulWidget {
  @override
  _ScanCodePageState createState() => _ScanCodePageState();
}

class _ScanCodePageState extends State<ScanCodePage>
    with TickerProviderStateMixin {
  AnimationController _animationController;
  bool openFlashlight;
  Timer _timer;

  QRViewController controller;
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  StreamSubscription subscription;

  @override
  void initState() {
    super.initState();
    openFlashlight = false;
    _initAnimation();
  }

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

  void _upState() {
    setState(() {});
  }

  void _clearAnimation() {
    _timer?.cancel();
    if (_animationController != null) {
      _animationController?.dispose();
      _animationController = null;
    }
  }

  void _initAnimation() {
    setState(() {
      _animationController = AnimationController(
          vsync: this, duration: Duration(milliseconds: 1000));
    });
    _animationController
      ..addListener(_upState)
      ..addStatusListener((state) {
        if (state == AnimationStatus.completed) {
          _timer = Timer(Duration(seconds: 1), () {
            _animationController?.reverse(from: 1.0);
          });
        } else if (state == AnimationStatus.dismissed) {
          _timer = Timer(Duration(seconds: 1), () {
            _animationController?.forward(from: 0.0);
          });
        }
      });
    _animationController.forward(from: 0.0);
  }

  Future setFlashlight() async {
    await controller?.toggleFlash();
    openFlashlight = await controller?.getFlashStatus();
    _upState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Material(
        color: Colors.black,
        child: LayoutBuilder(builder: (context, constraints) {
          final qrScanSize = constraints.maxWidth * 0.75;
          return Stack(
            children: <Widget>[
              QRView(
                key: qrKey,
                onQRViewCreated: _onQRViewCreated,
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  AppBar(
                    leading: BackButton(),
                    elevation: 0,
                    backgroundColor: Colors.transparent,
                  ),
                  SizedBox(
                    height: 100,
                  ),
                  Container(
                    padding: EdgeInsets.all(20),
                    child: SizedBox(
                      width: qrScanSize,
                      height: qrScanSize,
                      child: Stack(
                        children: [
                          CustomPaint(
                            painter: QrScanBoxPainter(
                              boxLineColor: Colors.lightGreenAccent,
                              animationValue: _animationController?.value ?? 0,
                              isForward: _animationController?.status ==
                                  AnimationStatus.forward,
                            ),
                            child: Container(),
                          ),
                          Positioned(
                            bottom: 10,
                            width: qrScanSize,
                            child: Align(
                              alignment: Alignment.bottomCenter,
                              child: GestureDetector(
                                behavior: HitTestBehavior.translucent,
                                onTap: setFlashlight,
                                child: Image(
                                  image: AssetImage(openFlashlight
                                      ? 'assets/tool_flashlight_close.png'
                                      : 'assets/tool_flashlight_open.png'),
                                  width: 35,
                                  height: 35,
                                  color: Colors.white,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Text(
                    "請將二維碼/條形碼置于方框中",
                    style: TextStyle(color: Colors.white),
                  ),
                ],
              )
            ],
          );
        }),
      ),
    );
  }

  void _onQRViewCreated(QRViewController controller) {
    setState(() {
      this.controller = controller;
    });
    if (subscription == null) {
      subscription = controller.scannedDataStream.listen((scanData) {
        //保證只接收一次數(shù)據(jù)
        subscription.cancel();
        Navigator.of(context).pop(scanData.code);
      });
    }
  }
}

class QrScanBoxPainter extends CustomPainter {
  final double animationValue;
  final bool isForward;
  final Color boxLineColor;

  QrScanBoxPainter(
      {@required this.animationValue,
      @required this.isForward,
      this.boxLineColor})
      : assert(animationValue != null),
        assert(isForward != null);

  @override
  void paint(Canvas canvas, Size size) {
    final borderRadius = BorderRadius.all(Radius.circular(12)).toRRect(
      Rect.fromLTWH(0, 0, size.width, size.height),
    );
    canvas.drawRRect(
      borderRadius,
      Paint()
        ..color = Colors.white54
        ..style = PaintingStyle.stroke
        ..strokeWidth = 1,
    );
    final borderPaint = Paint()
      ..color = Colors.greenAccent
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2;
    final path = new Path();
    // leftTop
    path.moveTo(0, 50);
    path.lineTo(0, 12);
    path.quadraticBezierTo(0, 0, 12, 0);
    path.lineTo(50, 0);
    // rightTop
    path.moveTo(size.width - 50, 0);
    path.lineTo(size.width - 12, 0);
    path.quadraticBezierTo(size.width, 0, size.width, 12);
    path.lineTo(size.width, 50);
    // rightBottom
    path.moveTo(size.width, size.height - 50);
    path.lineTo(size.width, size.height - 12);
    path.quadraticBezierTo(
        size.width, size.height, size.width - 12, size.height);
    path.lineTo(size.width - 50, size.height);
    // leftBottom
    path.moveTo(50, size.height);
    path.lineTo(12, size.height);
    path.quadraticBezierTo(0, size.height, 0, size.height - 12);
    path.lineTo(0, size.height - 50);

    canvas.drawPath(path, borderPaint);

    canvas.clipRRect(
        BorderRadius.all(Radius.circular(12)).toRRect(Offset.zero & size));

    // 繪制橫向網(wǎng)格
    final linePaint = Paint();
    final lineSize = size.height * 0.45;
    final leftPress = (size.height + lineSize) * animationValue - lineSize;
    linePaint.style = PaintingStyle.stroke;
    linePaint.shader = LinearGradient(
      colors: [Colors.transparent, boxLineColor],
      begin: isForward ? Alignment.topCenter : Alignment(0.0, 2.0),
      end: isForward ? Alignment(0.0, 0.5) : Alignment.topCenter,
    ).createShader(Rect.fromLTWH(0, leftPress, size.width, lineSize));
    for (int i = 0; i < size.height / 5; i++) {
      canvas.drawLine(
        Offset(
          i * 5.0,
          leftPress,
        ),
        Offset(i * 5.0, leftPress + lineSize),
        linePaint,
      );
    }
    for (int i = 0; i < lineSize / 5; i++) {
      canvas.drawLine(
        Offset(0, leftPress + i * 5.0),
        Offset(
          size.width,
          leftPress + i * 5.0,
        ),
        linePaint,
      );
    }
  }

  @override
  bool shouldRepaint(QrScanBoxPainter oldDelegate) =>
      animationValue != oldDelegate.animationValue;

  @override
  bool shouldRebuildSemantics(QrScanBoxPainter oldDelegate) =>
      animationValue != oldDelegate.animationValue;
}
以上代碼copy可直接使用瓣戚,UI顯示如下:
image.png

使用方法:

//打開掃一掃
  void _openScan() {
    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      return ScanCodePage();
    })).then((value) {
      print(value); //拿到掃描結果
    });
  }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末端圈,一起剝皮案震驚了整個濱河市焦读,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌舱权,老刑警劉巖矗晃,帶你破解...
    沈念sama閱讀 222,807評論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異宴倍,居然都是意外死亡张症,警方通過查閱死者的電腦和手機仓技,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,284評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來俗他,“玉大人脖捻,你說我怎么就攤上這事≌仔疲” “怎么了地沮?”我有些...
    開封第一講書人閱讀 169,589評論 0 363
  • 文/不壞的土叔 我叫張陵,是天一觀的道長羡亩。 經(jīng)常有香客問我摩疑,道長,這世上最難降的妖魔是什么畏铆? 我笑而不...
    開封第一講書人閱讀 60,188評論 1 300
  • 正文 為了忘掉前任雷袋,我火速辦了婚禮,結果婚禮上辞居,老公的妹妹穿的比我還像新娘楷怒。我一直安慰自己,他們只是感情好速侈,可當我...
    茶點故事閱讀 69,185評論 6 398
  • 文/花漫 我一把揭開白布率寡。 她就那樣靜靜地躺著,像睡著了一般倚搬。 火紅的嫁衣襯著肌膚如雪冶共。 梳的紋絲不亂的頭發(fā)上馋贤,一...
    開封第一講書人閱讀 52,785評論 1 314
  • 那天遥皂,我揣著相機與錄音,去河邊找鬼掖看。 笑死眨层,一個胖子當著我的面吹牛庙楚,可吹牛的內容都是我干的。 我是一名探鬼主播趴樱,決...
    沈念sama閱讀 41,220評論 3 423
  • 文/蒼蘭香墨 我猛地睜開眼馒闷,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了叁征?” 一聲冷哼從身側響起纳账,我...
    開封第一講書人閱讀 40,167評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎捺疼,沒想到半個月后疏虫,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,698評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,767評論 3 343
  • 正文 我和宋清朗相戀三年卧秘,在試婚紗的時候發(fā)現(xiàn)自己被綠了呢袱。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,912評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡翅敌,死狀恐怖羞福,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情蚯涮,我是刑警寧澤坯临,帶...
    沈念sama閱讀 36,572評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站恋昼,受9級特大地震影響看靠,放射性物質發(fā)生泄漏。R本人自食惡果不足惜液肌,卻給世界環(huán)境...
    茶點故事閱讀 42,254評論 3 336
  • 文/蒙蒙 一挟炬、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧嗦哆,春花似錦谤祖、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,746評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至橘券,卻和暖如春额湘,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背旁舰。 一陣腳步聲響...
    開封第一講書人閱讀 33,859評論 1 274
  • 我被黑心中介騙來泰國打工锋华, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人箭窜。 一個月前我還...
    沈念sama閱讀 49,359評論 3 379
  • 正文 我出身青樓毯焕,卻偏偏與公主長得像,于是被迫代替她去往敵國和親磺樱。 傳聞我的和親對象是個殘疾皇子纳猫,可洞房花燭夜當晚...
    茶點故事閱讀 45,922評論 2 361

推薦閱讀更多精彩內容

  • 效果 使用?? QR Code Scanner permission: Installation Add this ...
    樹生1995閱讀 13,927評論 17 2
  • 用到的組件 1、通過CocoaPods安裝 2竹捉、第三方類庫安裝 3芜辕、第三方服務 友盟社會化分享組件 友盟用戶反饋 ...
    SunnyLeong閱讀 14,629評論 1 180
  • 表情是什么,我認為表情就是表現(xiàn)出來的情緒活孩。表情可以傳達很多信息物遇。高興了當然就笑了,難過就哭了憾儒。兩者是相互影響密不可...
    Persistenc_6aea閱讀 125,389評論 2 7
  • 16宿命:用概率思維提高你的勝算 以前的我是風險厭惡者询兴,不喜歡去冒險,但是人生放棄了冒險起趾,也就放棄了無數(shù)的可能诗舰。 ...
    yichen大刀閱讀 6,059評論 0 4