introduce

Qr code as a carrier of information, which are widely used in every aspect of our lives, for example: use pay treasure payment, qr code to add friends, qr code promotion and so on, can, for example, plenty of examples, and if your application support qr code scanning, the growth of the user and the experience will double, if you are an application developer, welcome to use this qr code scanning plugin! And I hope you can give the project a STAR, thank you! Project address: github.com/rhymelph/r_…

use

You can find the plugin by searching r_scan on pub.dev and add the following code to pubspec.yaml

dependencies:
    r_scan: last version
Copy the code
  • Last version can be searched at pub.devr_scanget

Precautions for each device

  • The Android platform

Android6.0 system above please dynamic authorization, can be used with the permission_handler plug-in, the 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;
  }
Copy the code
  • The IOS platform

You need to add the following code to the info.plist file:

< key > NSCameraUsageDescription < / key > < string > scan qr code when you need to use your camera < / string > < key > NSPhotoLibraryUsageDescription < / key > <string> To scan qr code, you need to access your album </string> <key> IO. Flutter. Embedded_views_preview </key> <true/>
Copy the code

Guide package

import 'package:r_scan/r_scan.dart';
Copy the code

1. Scan the QR code of the file picture

final result=await RScan.scanImagePath('Your file path');
if(result.isNotEmpty){
    //result indicates the content of the QR code
}
Copy the code

2. Scan the qr code linked to the picture

final result=await RScan.scanImageUrl('Your image link');
if(result.isNotEmpty){
    //result indicates the content of the QR code
}
Copy the code

3. Scan the QR code of the memory image

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

4.(NEW)Scan the QR/barcode with the camera based on Texture

  • Step 1: Get an available camera
List<RScanCameraDescription> rScanCameras = await availableRScanCameras();;
Copy the code

If you get an available camera under the main() method, use the following code

List<RScanCameraDescription> rScanCameras;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  rScanCameras = awaitavailableRScanCameras(); runApp(...) ; }Copy the code
  • 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();
    // Check whether there is a camera available
    if(rScanCameras ! =null && rScanCameras.length > 0) {
    // Initialize the camera controller, generally rScanCameras[0] is rear, rScanCameras[1] is front camera
      _controller = RScanCameraController(
          rScanCameras[0], RScanCameraResolutionPreset.max) .. addListener(() {// Listen to scan results
          final result = _controller.result;
          if(result ! =null) {
            if (isFirst) {
            // If the qr code is scanned, return the result to the previous page
              Navigator.of(context).pop(result);
              isFirst = false; }}}).. initialize().then((_) {// Initialize the camera
          if(! mounted) {return; } setState(() {}); }); }}@override
  voiddispose() { _controller? .dispose();super.dispose();
  }

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

// Build the 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(); }}Copy the code

5.(deprecated) Scan qr/bar codes 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(() {// Listen for the qr code scanned
      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(// This prospect is written for myself
                child: RScanView(
                  controller: _controller,
                ),
              );
            } else {
              returnContainer(); }},),),); } 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; }}Copy the code

6. Turn on the flash/get the flash status

Directly called using an instance of the RScanController class

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

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

// Get the flash state
bool isOpen = await _controller.getFlashMode();
Copy the code

7.RScanResult(QR code scan result)

This object is returned when a QR code & barcode is scanned and contains the following content

class RScanResult {
  /// Bar code type
  final RScanBarType type;

  /// Attached information
  final String message;

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

The follow-up development

  1. Supports user-defined area trigger scan
  2. There’s more…