Flutter实战开发(1)------实现条形码和二维码扫描

实现条形码和二维码扫描

  • 前言
  • 准备工具
  • 引入插件
  • 具体实现

前言

前几天突发奇想就想做一个扫描二维码和条形码的demo,查阅了一些资料,发现有qrscan这个插件可以实现,就自己写了一个例子,供大家学习.

准备工具

这套课程是采用Android Studio进行开发的。当前在此之前请准备好Flutter开发环境,我这里就不进行讲解了。

引入插件

到pubspce.yaml中导包

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  qrscan: ^0.1.3

具体实现

import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;

void main() => runApp(MyApp());

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

  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String barcode = "";

  @override
  initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Scan barcodes and qr codes'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              Text(barcode),
              MaterialButton(
                onPressed: scan,
                child: Text("Scan"),
                color: Colors.blue,
                textColor: Colors.white,
              ),
            ],
          ),
        ),
      ),
    );
  }

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

class Qrscan {
}

Flutter实战开发(1)------实现条形码和二维码扫描_第1张图片
Flutter实战开发(1)------实现条形码和二维码扫描_第2张图片
Flutter实战开发(1)------实现条形码和二维码扫描_第3张图片

Flutter实战开发(1)------实现条形码和二维码扫描_第4张图片

这篇博客就先分享到这里了,后续我还有添加一些功能的,喜欢的朋友关注一下

你可能感兴趣的:(Flutter,Flutter基本功能介绍,Flutter扫描)