Flutter进阶第11篇: 调用原生硬件Api实现扫码 扫描条形码 扫描二维码

效果图:

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

第一步:

导入第三方库:barcode_scan

第二步:

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

第三步:

3.1 的 编 辑 你 的 d android 的 目 录 下 面 的 e build.gradle ( Edit your project-level
build.gradle file to look like this)
注意: : 官方文档配置的 kotlin_version 的版本是 1.2.31,但是实际发现 1.2.31
会报错。所以本项目使用 1.3.0。

buildscript {
ext.kotlin_version = '1.3.0'
...
dependencies {
...
classpath
"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}

第四步:编辑你 的 p android/app 的 目 录下 面 的 e build.gradle ( Edit your app-levelbuild.gradle file to look like this)

apply plugin: 'kotlin-android'
...
dependencies {
implementation
"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
...
}
import 'package:flutter/material.dart';

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

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

  _ScanPageState createState() => _ScanPageState();
}

class _ScanPageState extends State<ScanPage> {
  String barcode;

  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');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.photo_camera),
          onPressed: _scan,
        ),
        appBar: AppBar(
          title: Text("扫码"),
        ),
        body: Text("${barcode}")
    );
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王睿丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值