flutter实现条形码二维码扫描

flutter实现条形码二维码扫描

我们使用到的第三方插件为barcode_scan2
地址为:https://pub.flutter-io.cn/packages/barcode_scan2

准备工作

安卓使用此插件需要注意以下几点:

  1. 相机权限添加
    将相机权限添加到您的 AndroidManifest 中.xml在这里插入图片描述
<uses-permission android:name="android.permission.CAMERA" />
  1. 这个插件是用 Kotlin 编写的。因此,您需要向项目添加 Kotlin 支持。
    编辑项目级 build.gradle 文件,使其如下所示:
    在这里插入图片描述
buildscript {
    ext.kotlin_version = '1.3.61'
    // ...
    dependencies {
        // ...
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
// ...

编辑您的应用级 build.gradle 文件,使其如下所示:
在这里插入图片描述

apply plugin: 'kotlin-android'
// ...
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    // ...
}

  1. minSdkVersion 18 以上

在这里插入图片描述

使用

import 'package:flutter/material.dart';
import 'package:barcode_scan2/barcode_scan2.dart';

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

  @override
  State<BarcodeScanPage> createState() => _BarcodeScanPageState();
}

class _BarcodeScanPageState extends State<BarcodeScanPage> {

//调用相机扫描条形码二维码的方法
  void _doBarcodeScan() async {
    var options = const ScanOptions(
      //是否自动打开闪光灯
      autoEnableFlash: true,
      strings: {
        'cancel':'取消',
        'flash_on':'打开flash',
        'flash_off':'关闭flash'
      }
    );
    var result = await BarcodeScanner.scan(options: options);
    print(result.type);
    print(result.rawContent);
    print(result.format);
    print(result.formatNote);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("扫码演示"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          ElevatedButton(
            onPressed: _doBarcodeScan,
            child: Text("扫码条形码 二维码"),
          )
        ],
      ),
    );
  }
}

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: BarcodeScanPage(),
    );
  }
}

请添加图片描述
请添加图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值