Flutter self made plug-in R_ Scan QR Code & bar code scanning (supporting file, URL, memory and camera)

Time:2021-7-24

Flutter self made plug-in R_ Scan QR Code & bar code scanning (supporting file, URL, memory and camera)

introduce

Two dimensional code as a carrier of information, widely used in all aspects of our lives, such as: Alipay payment, two-dimensional code plus friends, two-dimensional code promotion and so on, examples of many examples, and if your application supports two-dimensional code scanning, users and experience will double the growth, if you are the developer of the application, Welcome to this QR code scanning plug-in! And hope to give the project a star, thank you! Project address:https://github.com/rhymelph/r…

use

You can search on the pub.dev websiter_scanYou can find the plug-in and add the following code topubspec.yamlfile

dependencies:
    r_scan: last version
  • The last version can be searched on the pub.dev websiter_scanobtain

Precautions for each equipment

  • Under Android platform

For Android 6.0 system, please authorize dynamically, which can be combined withpermission_handlerThe plug-in code is as follows:

import 'package:permission_handler/permission_handler.dart';

Future<bool> canReadStorage() async {
    if(Platform.isIOS) return true;
    var status = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.storage);
    if (status != PermissionStatus.granted) {
      var future = await PermissionHandler()
          .requestPermissions([PermissionGroup.storage]);
      for (final item in future.entries) {
        if (item.value != PermissionStatus.granted) {
          return false;
        }
      }
    } else {
      return true;
    }
    return true;
  }

Future<bool> canOpenCamera() async {
    var status =
        await PermissionHandler().checkPermissionStatus(PermissionGroup.camera);
    if (status != PermissionStatus.granted) {
      var future = await PermissionHandler()
          .requestPermissions([PermissionGroup.camera]);
      for (final item in future.entries) {
        if (item.value != PermissionStatus.granted) {
          return false;
        }
      }
    } else {
      return true;
    }
    return true;
  }
  • Under IOS platform

Need ininfo.plistAdd the following code under the file:

<key>NSCameraUsageDescription</key>
    < string > when scanning QR code, you need to use your camera < / String >
    <key>NSPhotoLibraryUsageDescription</key>
    < string > when scanning QR code, you need to access your album < / String >
    <key>io.flutter.embedded_views_preview</key>
    <true/>

Guide Package

import 'package:r_scan/r_scan.dart';

1. Scan the QR code of documents and pictures

Final result = await rscan.scanimagepath ('your file path ');
if(result.isNotEmpty){
    //Result is the content of QR code
}

2. Scan picture link QR code

Final result = await rscan.scanimagepath ('your picture link ');
if(result.isNotEmpty){
    //Result is the content of QR code
}

3. Scan memory picture QR code

ByteData data=await rootBundle.load('images/qrCode.png');
final result=await RScan.scanImageMemory(data.buffer.asUint8List());
if(result.isNotEmpty){
    //Result is the content of QR code
}

4. (New) scan QR code / barcode with camera based on texture

  • Step 1: get available cameras
List<RScanCameraDescription> rScanCameras = await availableRScanCameras();;

If you aremain()Method, please use the following code

List<RScanCameraDescription> rScanCameras;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  rScanCameras = await availableRScanCameras();
  runApp(...);
}
  • Step 2: start using
class RScanCameraDialog extends StatefulWidget {
  @override
  _RScanCameraDialogState createState() => _RScanCameraDialogState();
}

class _RScanCameraDialogState extends State<RScanCameraDialog> {
  RScanCameraController _controller;
  bool isFirst = true;

  @override
  void initState() {
    super.initState();
    //Determine whether a camera is currently available
    if (rScanCameras != null && rScanCameras.length > 0) {
    //Initialize the camera controller. Generally, rscancameras [0] is the rear camera and rscancameras [1] is the front camera
      _controller = RScanCameraController(
          rScanCameras[0], RScanCameraResolutionPreset.max)
        ..addListener(() {
        //Monitoring code scanning return result
          final result = _controller.result;
          if (result != null) {
            if (isFirst) {
            //If the QR code is scanned, the result will be returned to the previous page
              Navigator.of(context).pop(result);
              isFirst = false;
            }
          }
        })
        ..initialize().then((_) {
        //Initialize camera
          if (!mounted) {
            return;
          }
          setState(() {});
        });
    }
  }

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

  @override
  Widget build(BuildContext context) {
  //Determine if a camera is available
    if (rScanCameras == null || rScanCameras.length == 0) {
      return Scaffold(
        body: Container(
          alignment: Alignment.center,
          child: Text('not have available camera'),
        ),
      );
    }
    //Judge that if the camera is not initialized, give it a load page
    if (!_controller.value.isInitialized) {
      return Container();
    }
    //Get camera
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: <Widget>[
          ScanImageView(
            child: AspectRatio(
            //Get the aspectratio of the camera
              aspectRatio: _controller.value.aspectRatio,
              child: RScanCamera(_controller),
            ),
          ),
          //Flash
          Align(
              alignment: Alignment.bottomCenter,
              child: FutureBuilder(
                future: getFlashMode(),
                builder: _buildFlashBtn,
              ))
        ],
      ),
    );
  }
  //Get whether the flash is on
  Future<bool> getFlashMode() async {
    bool isOpen = false;
    try {
      isOpen = await _controller.getFlashMode();
    } catch (_) {}
    return isOpen;
  }

//Build flash button
  Widget _buildFlashBtn(BuildContext context, AsyncSnapshot<bool> snapshot) {
    return snapshot.hasData
        ? Padding(
      padding:  EdgeInsets.only(bottom:24+MediaQuery.of(context).padding.bottom),
      child: IconButton(
          icon: Icon(snapshot.data ? Icons.flash_on : Icons.flash_off),
          color: Colors.white,
          iconSize: 46,
          onPressed: () {
            if (snapshot.data) {
              _controller.setFlashMode(false);
            } else {
              _controller.setFlashMode(true);
            }
            setState(() {});
          }),
    )
        : Container();
  }
}

5. (deprecated) scan QR code / barcode with camera based on platformview

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:r_scan/r_scan.dart';

class RScanDialog extends StatefulWidget {
  @override
  _RScanDialogState createState() => _RScanDialogState();
}

class _RScanDialogState extends State<RScanDialog> {
  RScanController _controller;

  @override
  void initState() {
    super.initState();
    initController();
  }
  bool isFirst=true;


  Future<void> initController() async {
    _controller = RScanController();
    _ Controller. AddListener (() {// monitor the scanned QR code
      final result = _controller.result;
      if (result != null) {
        if(isFirst){
          Navigator.of(context).pop(result);
          isFirst=false;
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.black,
        body: FutureBuilder<bool>(
          future: canOpenCameraView(),
          builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
            if (snapshot.hasData && snapshot.data == true) {
              Return scanimageview (// the foreground written for yourself
                child: RScanView(
                  controller: _controller,
                ),
              );
            } else {
              return Container();
            }
          },
        ),
      ),
    );
  }

  Future<bool> canOpenCameraView() async {
    var status =
        await PermissionHandler().checkPermissionStatus(PermissionGroup.camera);
    if (status != PermissionStatus.granted) {
      var future = await PermissionHandler()
          .requestPermissions([PermissionGroup.camera]);
      for (final item in future.entries) {
        if (item.value != PermissionStatus.granted) {
          return false;
        }
      }
    } else {
      return true;
    }
    return true;
  }
}

6. Turn on the flash / get the flash status

useRScanControllerClass

//Turn off the flash
await _controller.setFlashMode(false);

//Turn on the flash
await _controller.setFlashMode(true);

//Get flash status
bool isOpen = await _controller.getFlashMode();

7. Rscanresult (QR code scanning result)

When the QR Code & barcode is scanned, the object will be returned, including the following contents

class RScanResult {
  ///Barcode type
  final RScanBarType type;

  ///Attached information
  final String message;

  ///The area corresponding to the barcode contains [x, y] coordinates
  final List<RScanPoint> points;
}

Subsequent development

  1. Support custom area trigger scanning
  2. There’s more

Recommended Today

C # regular implementation of UBB parsing class code

The parsed code can pass XHTML   one   Strict verification;It includes title, link, font, alignment, picture, reference, list and other functions  Ubb.ReadMe.htm UBB code description title [H1] title I [/ H1] Title I [H2] Title II [/ H2] Title II [H1] Title III [/ H1] Title III [H4] Title IV [/ H4] Title IV […]