Flutter插件keyri_v3的使用_keyri_v3是一个用于支持Keyri QR登录系统的Flutter移动应用插件

Flutter插件keyri_v3的使用_keyri_v3是一个用于支持Keyri QR登录系统的Flutter移动应用插件

关于keyri_v3

这是一个用于支持Keyri QR登录系统的Flutter移动应用插件。完整的文档可以在以下链接中找到:https://docs.keyri.com/flutter

该插件基于Keyri iOS (Swift) 和 Android (Kotlin) 包构建,需要iOS 14及以上版本和Android API级别23及以上版本才能正常工作。这两个包都没有任何第三方依赖。

示例代码

示例代码文件:example/lib/main.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:keyri_v3/keyri.dart';
import 'package:keyri_v3/keyri_detections_config.dart';
import 'package:keyri_v3/keyri_fingerprint_event.dart';

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

TextEditingController appKeyController = TextEditingController();
TextEditingController publicApiKeyController = TextEditingController();
TextEditingController serviceEncryptionKeyController = TextEditingController();
TextEditingController usernameController = TextEditingController();

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Keyri Example',
        theme: ThemeData(primarySwatch: Colors.blue),
        home: const KeyriHomePage(title: 'Keyri Example'));
  }
}

class KeyriHomePage extends StatefulWidget {
  const KeyriHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<KeyriHomePage> createState() => _KeyriHomePageState();
}

class _KeyriHomePageState extends State<KeyriHomePage> {
  final EventType _eventType = EventType.custom("custom");

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 30.0),
                // 调整水平填充
                child: Center(
                  child: Column(
                    children: [
                      TextFormField(
                          controller: appKeyController,
                          decoration: InputDecoration(
                            labelText: "输入应用密钥",
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10.0),
                            ),
                          )),
                      const SizedBox(height: 5),
                      TextFormField(
                          controller: publicApiKeyController,
                          decoration: InputDecoration(
                            labelText: "输入公共API密钥",
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10.0),
                            ),
                          )),
                      const SizedBox(height: 5),
                      TextFormField(
                          controller: serviceEncryptionKeyController,
                          decoration: InputDecoration(
                            labelText: "输入服务加密密钥",
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10.0),
                            ),
                          )),
                      const SizedBox(height: 30),
                      TextFormField(
                          controller: usernameController,
                          decoration: InputDecoration(
                            labelText: "输入用户名",
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10.0),
                            ),
                          )),
                    ],
                  ),
                ),
              ),
              button(_sendEvent, '发送事件'),
              button(_login, '登录'),
              button(_register, '注册'),
              button(_getCorrectedTimestampSeconds, '获取时间戳'),
              button(_generateAssociationKey, '生成关联密钥'),
              button(_getAssociationKey, '获取关联密钥'),
              button(_removeAssociationKey, '移除关联密钥'),
              button(_listAssociationKeys, '列出关联密钥'),
              button(_listUniqueAccounts, '列出唯一账户'),
              button(_generateSignature, '生成签名')
            ],
          ),
        ),
      ),
    );
  }

  Keyri? initKeyri() {
    var appKey = appKeyController.text;
    String? publicApiKey = publicApiKeyController.text;
    String? serviceEncryptionKey = serviceEncryptionKeyController.text;

    if (appKey.isNotEmpty) {
      if (publicApiKey.isEmpty) {
        publicApiKey = null;
      }

      if (serviceEncryptionKey.isEmpty) {
        serviceEncryptionKey = null;
      }

      return Keyri.primary(appKey,
          publicApiKey: publicApiKey,
          serviceEncryptionKey: serviceEncryptionKey,
          detectionsConfig: KeyriDetectionsConfig(blockTamperDetection: true));
    } else {
      _showMessage('应用密钥是必需的!');
    }

    return null;
  }

  Future<void> _login() async {
    Keyri? keyri = initKeyri();

    if (keyri == null) return;

    String? publicUserId = usernameController.text;

    if (publicUserId.isEmpty) {
      publicUserId = null;
    }

    keyri
        .login(publicUserId: publicUserId)
        .then((loginObject) =>
            _showMessage('登录对象: ${json.encode(loginObject.toJson())}'))
        .catchError((error, stackTrace) => _processError(error));
  }

  Future<void> _register() async {
    Keyri? keyri = initKeyri();

    if (keyri == null) return;

    String? publicUserId = usernameController.text;

    if (publicUserId.isEmpty) {
      publicUserId = null;
    }

    keyri
        .register(publicUserId: publicUserId)
        .then((registerObject) => _showMessage(
            '注册对象: ${json.encode(registerObject.toJson())}'))
        .catchError((error, stackTrace) => _processError(error));
  }

  Future<void> _getCorrectedTimestampSeconds() async {
    Keyri? keyri = initKeyri();

    if (keyri == null) return;

    String? publicUserId = usernameController.text;

    if (publicUserId.isEmpty) {
      publicUserId = null;
    }

    keyri
        .getCorrectedTimestampSeconds()
        .then((timestamp) => _showMessage('时间戳: $timestamp'))
        .catchError((error, stackTrace) => _processError(error));
  }

  void _generateAssociationKey() {
    Keyri? keyri = initKeyri();

    if (keyri == null) return;

    String? publicUserId = usernameController.text;

    if (publicUserId.isEmpty) {
      publicUserId = null;
    }

    keyri
        .generateAssociationKey(publicUserId: publicUserId)
        .then((key) => _showMessage('生成的密钥: $key'))
        .catchError((error, stackTrace) => _processError(error));
  }

  void _getAssociationKey() {
    Keyri? keyri = initKeyri();

    if (keyri == null) return;

    String? publicUserId = usernameController.text;

    if (publicUserId.isEmpty) {
      publicUserId = null;
    }

    keyri
        .getAssociationKey(publicUserId: publicUserId)
        .then((key) => _showMessage('密钥: $key'))
        .catchError((error, stackTrace) => _processError(error));
  }

  void _generateSignature() {
    Keyri? keyri = initKeyri();

    if (keyri == null) return;

    int timestamp = DateTime.now().millisecondsSinceEpoch;

    String? publicUserId = usernameController.text;

    if (publicUserId.isEmpty) {
      publicUserId = null;
    }

    keyri
        .generateUserSignature(
            publicUserId: publicUserId, data: timestamp.toString())
        .then((signature) => _showMessage('签名: $signature'))
        .catchError((error, stackTrace) => _processError(error));
  }

  void _removeAssociationKey() {
    Keyri? keyri = initKeyri();

    if (keyri == null) return;

    String? userId = usernameController.text;

    if (userId.isNotEmpty) {
      keyri
          .removeAssociationKey(userId)
          .then((_) => _showMessage('密钥已移除'))
          .catchError((error, stackTrace) => _processError(error));
    } else {
      _showMessage('publicUserId 不应为空');
    }
  }

  void _listAssociationKeys() {
    Keyri? keyri = initKeyri();

    if (keyri == null) return;

    keyri
        .listAssociationKeys()
        .then((keys) => _showMessage(json.encode(keys)))
        .catchError((error, stackTrace) => _processError(error));
  }

  void _listUniqueAccounts() {
    Keyri? keyri = initKeyri();

    if (keyri == null) return;

    keyri
        .listUniqueAccounts()
        .then((keys) => _showMessage(json.encode(keys)))
        .catchError((error, stackTrace) => _processError(error));
  }

  void _sendEvent() async {
    Keyri? keyri = initKeyri();

    if (keyri == null) return;

    String? publicUserId = usernameController.text;

    if (publicUserId.isEmpty) {
      publicUserId = null;
    }

    keyri
        .sendEvent(
            publicUserId: usernameController.text,
            eventType: _eventType,
            success: true)
        .then((fingerprintEventResponse) => _showMessage("事件已发送"))
        .catchError((error, stackTrace) => _processError(error));
  }

  void _processError(dynamic error) {
    if (error is PlatformException) {
      _showMessage(error.message ?? "发生错误");
    } else {
      _showMessage(error.toString());
    }
  }

  void _showMessage(String message) {
    ScaffoldMessenger.of(context)
        .showSnackBar(SnackBar(content: Text(message)));
  }

  Widget button(VoidCallback onPressedCallback, String text) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        foregroundColor: Colors.white,
        backgroundColor: Colors.deepPurple,
      ),
      onPressed: onPressedCallback,
      child: Text(text),
    );
  }
}

更多关于Flutter插件keyri_v3的使用_keyri_v3是一个用于支持Keyri QR登录系统的Flutter移动应用插件的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter插件keyri_v3的使用_keyri_v3是一个用于支持Keyri QR登录系统的Flutter移动应用插件的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中使用未知功能的插件时,尽管我们没有具体的功能描述,但通常可以按照插件的官方文档或示例代码来进行集成和使用。由于keyri_v3这个插件的具体信息未定义,以下是一个通用的Flutter插件集成和使用方法的示例代码框架。请注意,实际使用时需要根据keyri_v3插件的实际API进行调整。

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

dependencies:
  flutter:
    sdk: flutter
  keyri_v3: ^x.y.z  # 替换为实际的版本号

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

接下来,在你的Flutter应用中导入并使用该插件。以下是一个简单的示例代码,展示如何初始化插件并调用一个假设的方法(由于功能未知,这里用someUnknownFunction代替):

import 'package:flutter/material.dart';
import 'package:keyri_v3/keyri_v3.dart';  // 假设这是插件的导入路径

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

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late KeyriV3 _keyriV3;  // 假设插件的主要类名为KeyriV3

  @override
  void initState() {
    super.initState();
    // 初始化插件
    _keyriV3 = KeyriV3();
    
    // 调用假设的未知功能方法
    _callUnknownFunction();
  }

  Future<void> _callUnknownFunction() async {
    try {
      // 假设这个方法存在并返回一个结果
      var result = await _keyriV3.someUnknownFunction();
      print('Result from unknown function: $result');
    } catch (e) {
      print('Error calling unknown function: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo Home Page'),
      ),
      body: Center(
        child: Text('Waiting for unknown function result...'),
      ),
    );
  }
}

请注意以下几点:

  1. 插件类名和方法名:上面的代码假设插件的主要类名为KeyriV3,并且有一个名为someUnknownFunction的方法。实际使用时,你需要根据插件的文档或源代码来确定正确的类名和方法名。

  2. 异步调用:由于Flutter插件通常涉及与原生代码的交互,因此方法调用往往是异步的。在上面的示例中,我们使用await关键字来等待异步方法的结果。

  3. 错误处理:在调用插件方法时,最好添加错误处理逻辑,以便在方法调用失败时能够给出适当的反馈。

  4. 插件文档:由于keyri_v3是一个未知功能的插件,强烈建议查阅其官方文档或源代码以了解具体的API和使用方法。

  5. 插件版本:确保你使用的是最新版本的插件,以避免已知的bug或兼容性问题。

由于keyri_v3的具体功能未知,以上代码仅提供了一个通用的集成和使用框架。实际使用时,请根据插件的实际情况进行调整。

回到顶部