Flutter二维码扫描插件klippa_scanner_sdk的使用

发布于 1周前 作者 wuwangju 来自 Flutter

Flutter二维码扫描插件klippa_scanner_sdk的使用

SDK usage

请注意,您需要一个许可证才能使用此SDK。如果您想使用我们的扫描器,请联系 Klippa

Getting started

Android

编辑android/key.properties文件,如果不存在则创建它,并添加SDK凭证:

klippa.scanner.sdk.username={your-username}
klippa.scanner.sdk.password={your-password}

{your-username}{your-password} 替换为 Klippa 提供的值。

iOS

编辑 ios/Podfile 文件,添加 Klippa CocoaPod:

platform :ios, '13.0'
ENV['KLIPPA_SCANNER_SDK_USERNAME'] = '{your-username}'
ENV['KLIPPA_SCANNER_SDK_PASSWORD'] = '{your-password}'

target 'Runner' do
    // ... other instructions
    
    if "#{ENV['KLIPPA_SCANNER_SDK_URL']}" == ""
        ENV['KLIPPA_SCANNER_SDK_URL'] = File.read(File.join(File.dirname(File.realpath(__FILE__)), '.symlinks', 'plugins', 'klippa_scanner_sdk', 'ios', 'sdk_repo')).strip
    end

    if "#{ENV['KLIPPA_SCANNER_SDK_VERSION']}" == ""
        ENV['KLIPPA_SCANNER_SDK_VERSION'] = File.read(File.join(File.dirname(File.realpath(__FILE__)), '.symlinks', 'plugins', 'klippa_scanner_sdk', 'ios', 'sdk_version')).strip
    end

    pod 'Klippa-Scanner', podspec: "#{ENV['KLIPPA_SCANNER_SDK_URL']}/#{ENV['KLIPPA_SCANNER_SDK_USERNAME']}/#{ENV['KLIPPA_SCANNER_SDK_PASSWORD']}/KlippaScanner/#{ENV['KLIPPA_SCANNER_SDK_VERSION']}.podspec"
end

{your-username}{your-password} 替换为 Klippa 提供的值。

编辑 ios/{project-name}/Info.plist 文件并添加 NSCameraUsageDescription 值:

<key>NSCameraUsageDescription</key>
<string>Access to your camera is needed to photograph documents.</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Access to your photo library is used to save the images of documents.</string>

Flutter

pubspec.yaml 文件中添加 klippa_scanner_sdk 作为依赖项:

dependencies:
  flutter:
    sdk: flutter

  klippa_scanner_sdk: ^x.y.z

  # Rest of dependencies

Usage

import 'package:klippa_scanner_sdk/klippa_scanner_sdk.dart';

var config = CameraConfig();

try {
  var result = await KlippaScannerSdk.startSession(config, '{insert-license-here}');
} on PlatformException catch (e) {
  print('Failed to start session ' + e.toString());
}

示例代码

以下是一个完整的示例应用:

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

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

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _scannerResult = 'Unknown';

  String license = "{your-license}";

  [@override](/user/override)
  void initState() {
    super.initState();
  }

  void _startSession() async {
    String sessionResultText = 'Unknown';
    var config = CameraConfig();
    // setup your scanner
    config.storeImagesToCameraRol = true;
    try {
      var result = await KlippaScannerSdk.startSession(config, license);
      sessionResultText = 'Finished';
      print(result);
    } on PlatformException catch (e) {
      sessionResultText = 'Failed to start session ' + e.toString();
    }

    setState(() {
      _scannerResult = sessionResultText;
    });

    if (!mounted) return;
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Text('Scanner result: $_scannerResult\n'),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _startSession,
          tooltip: 'Start session',
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

更多关于Flutter二维码扫描插件klippa_scanner_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter二维码扫描插件klippa_scanner_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用klippa_scanner_sdk插件进行二维码扫描的代码示例。klippa_scanner_sdk是一个强大的二维码扫描库,适用于Flutter应用。

首先,确保你已经在pubspec.yaml文件中添加了klippa_scanner_sdk依赖:

dependencies:
  flutter:
    sdk: flutter
  klippa_scanner_sdk: ^最新版本号  # 请替换为最新版本号

然后,运行flutter pub get来安装依赖。

接下来,你可以在你的Flutter项目中按照以下步骤使用klippa_scanner_sdk进行二维码扫描:

1. 导入必要的包

在你的Dart文件中,导入klippa_scanner_sdk包:

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

2. 配置扫描器

你可以使用KlippaScannerController来配置和管理扫描器。以下是一个简单的示例,展示了如何启动扫描器并处理扫描结果:

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Klippa Scanner Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ScannerScreen(),
    );
  }
}

class ScannerScreen extends StatefulWidget {
  @override
  _ScannerScreenState createState() => _ScannerScreenState();
}

class _ScannerScreenState extends State<ScannerScreen> {
  late KlippaScannerController _scannerController;

  @override
  void initState() {
    super.initState();
    _scannerController = KlippaScannerController(
      onScanResult: (result) {
        // 处理扫描结果
        Navigator.of(context).pop(result);
        showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: Text('扫描结果'),
              content: Text(result),
              actions: <Widget>[
                TextButton(
                  child: Text('关闭'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      },
    );
  }

  @override
  void dispose() {
    _scannerController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('二维码扫描'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            // 启动扫描器
            await _scannerController.startScanner();
          },
          child: Text('开始扫描'),
        ),
      ),
    );
  }
}

3. 处理权限

在Android和iOS上,二维码扫描通常需要相机权限。确保在AndroidManifest.xmlInfo.plist中添加了必要的权限声明。

Android (AndroidManifest.xml)

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

iOS (Info.plist)

<key>NSCameraUsageDescription</key>
<string>需要访问相机以扫描二维码</string>

4. 请求权限

在实际应用中,你还需要在运行时请求相机权限。可以使用permission_handler插件来处理权限请求。以下是如何集成permission_handler并请求相机权限的示例:

pubspec.yaml中添加permission_handler依赖:

dependencies:
  permission_handler: ^最新版本号  # 请替换为最新版本号

然后在你的代码中请求权限:

import 'package:permission_handler/permission_handler.dart';

// 在ScannerScreen类的initState方法中添加以下代码
@override
void initState() {
  super.initState();

  // 请求相机权限
  _requestCameraPermission().then((status) {
    if (status == PermissionStatus.granted) {
      // 权限已授予,初始化扫描器
      _scannerController = KlippaScannerController(
        onScanResult: (result) {
          // 处理扫描结果
          Navigator.of(context).pop(result);
          showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                title: Text('扫描结果'),
                content: Text(result),
                actions: <Widget>[
                  TextButton(
                    child: Text('关闭'),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            },
          );
        },
      );
    } else {
      // 权限被拒绝,显示提示信息
      showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('权限被拒绝'),
            content: Text('需要相机权限才能扫描二维码'),
            actions: <Widget>[
              TextButton(
                child: Text('打开设置'),
                onPressed: () {
                  openAppSettings();
                },
              ),
            ],
          );
        },
      );
    }
  });
}

Future<PermissionStatus> _requestCameraPermission() async {
  var status = await Permission.camera.status;
  if (!status.isGranted) {
    var result = await Permission.camera.request();
    if (result.isPermanentlyDenied) {
      // 用户已永久拒绝权限,打开应用设置
      openAppSettings();
    }
    return result;
  } else {
    return status;
  }
}

确保在ios/Runner/Info.plistandroid/app/src/main/AndroidManifest.xml中正确配置了相机权限。

以上代码展示了如何在Flutter应用中使用klippa_scanner_sdk进行二维码扫描,包括初始化扫描器、请求相机权限以及处理扫描结果。希望这对你有帮助!

回到顶部