首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Flutter中如何实现扫码

Flutter中如何实现扫码

作者头像
拉维
发布2019-09-16 16:23:08
发布2019-09-16 16:23:08
6K0
举报
文章被收录于专栏:iOS小生活iOS小生活

我们通过 barcode_scan 这个库来实现二维码、条形码的扫描。

使用代码如下:

代码语言:javascript
复制
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:barcode_scan/barcode_scan.dart';

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

  _SaveLocalDataPageState createState() => _SaveLocalDataPageState();
}

class _SaveLocalDataPageState extends State<SaveLocalDataPage> {
  String _scanResultStr = "";

  //扫码
  Future _scan() async {
    //利用try-catch来进行异常处理
    try {
      //调起摄像头开始扫码
      String barcode = await BarcodeScanner.scan();
      setState(() {
        return this._scanResultStr = barcode;
      });
    } on PlatformException catch (e) {
      //如果没有调用摄像头的权限,则提醒
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        setState(() {
          return this._scanResultStr =
              'The user did not grant the camera permission!';
        });
      } else {
        setState(() {
          return this._scanResultStr = 'Unknown error: $e';
        });
      }
    } on FormatException {
      setState(() => this._scanResultStr =
          'null (User returned using the "back"-button before scanning anything. Result)');
    } catch (e) {
      setState(() => this._scanResultStr = 'Unknown error: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("本地数据存储")),
      body: Column(
        children: <Widget>[
          RaisedButton(
            onPressed: () {
              _scan();
            },
            child: Text("扫码"),
          ),
          Text(_scanResultStr),
        ],
      ),
    );
  }
}

运行效果如下:

关于barcode_scan这个扫码组件,针对iOS和Android环境,都要进行对应的环境配置。iOS的配置相对简单,Android的配置就比较繁琐了。

后期我们在做项目的时候,自己根据文档进行对应配置,如果遇到了困难,可以参考大地老师flutter基础视频的第41讲。

以上。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-09-14,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档