Flutter一次性密码(OTP)检测插件otp_detection_flutter的使用

Flutter一次性密码(OTP)检测插件otp_detection_flutter的使用

每日,我们都会使用一次性密码(OTP)进行银行交易的账户验证到普通的移动登录验证。根据用途的不同,OTP的长度可能会有所不同。这种变化是因为为交易添加了安全措施。此外,我们还为OTP设置了计时器,因此自动填充OTP是每个应用的必备功能。对于iOS,自动填充是默认功能,但在Android上,我们需要该功能。此插件满足了这一需求。

开始使用

PinFieldAutoFill

PinFieldAutoFill(
  decoration: // UnderlineDecoration, BoxLooseDecoration 或 BoxTightDecoration,请参阅 https://github.com/TinoGuo/pin_input_text_field 获取更多信息,
  currentCode: // 预填充一个代码
  onCodeSubmitted: // 代码提交回调
  onCodeChanged: // 代码更改回调
  codeLength: // 代码长度,默认为6
),

TextFieldPinAutoFill

TextFieldPinAutoFill(
  decoration: // 基本的 InputDecoration
  currentCode: // 预填充一个代码
  onCodeSubmitted: // 代码提交回调
  onCodeChanged: // 代码更改回调
  codeLength: // 代码长度,默认为6
),

Android SMS约束

为了接收到代码,它需要遵循一些规则,如这里描述:

  • 不得超过140字节
  • 包含客户端发送回服务器以完成验证流程的一次性代码
  • 以识别您的应用程序的11个字符哈希字符串结尾 一个SMS的例子可能如下:
ExampleApp: 您的代码是123456
FA+9qCX9VSu

自定义CodeAutoFill

如果您想创建一个自定义小部件,它将自动填充短信代码,您可以使用CodeAutoFill混入,它将为您提供以下功能:

listenForCode() // 当接收到短信代码时,从本地插件监听,需要在您的`initState`中调用。
cancel() // 释放从本地插件订阅的短信代码,需要在您的`dispose`中调用。
codeUpdated() // 收到代码时被调用,可以通过字段`code`访问值。
unregisterListener() // 注销广播接收器,需要在您的`dispose`中调用。

完整示例Demo

main.dart

import 'package:flutter/material.dart';
import 'package:otp_detection_flutter_example/mobile_number_verification.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter OTP自动检测',
      home: MobileNumberVerification(),
    );
  }
}

mobile_number_verification.dart

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

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

class _MobileNumberVerificationState extends State<MobileNumberVerification> {
  final TextEditingController _controller = TextEditingController();

  [@override](/user/override)
  void initState() {
    super.initState();
    // 监听短信代码
    OtpDetect().listenForCode();
  }

  [@override](/user/override)
  void dispose() {
    // 取消监听
    OtpDetect().cancel();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('手机验证'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _controller,
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(
                labelText: '手机号码',
              ),
            ),
            SizedBox(height: 20),
            PinFieldAutoFill(
              decoration: BoxLooseDecoration(
                strokeColorBuilder: FixedColorBuilder(Colors.black),
              ),
              codeLength: 6,
              onCodeSubmitted: (String code) {
                // 处理提交的代码
                print('提交的代码: $code');
              },
              onCodeChanged: (String? code) {
                // 处理代码更改
                if (code?.length == 6) {
                  print('输入的代码: $code');
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter一次性密码(OTP)检测插件otp_detection_flutter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter一次性密码(OTP)检测插件otp_detection_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


otp_detection_flutter 是一个用于在 Flutter 应用中自动检测和提取短信中的一次性密码(OTP)的插件。它可以帮助你简化用户输入 OTP 的流程,提升用户体验。

以下是使用 otp_detection_flutter 插件的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 otp_detection_flutter 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  otp_detection_flutter: ^1.0.0  # 请检查最新版本

然后运行 flutter pub get 来获取依赖。

2. 配置权限

为了读取短信,你需要在 AndroidManifest.xml 文件中添加以下权限:

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>

对于 iOS,你需要在 Info.plist 文件中添加以下权限:

<key>NSMotionUsageDescription</key>
<string>We need access to read SMS for OTP detection.</string>

3. 请求权限

在运行时,你需要请求用户授予读取短信的权限。你可以使用 permission_handler 插件来请求权限:

import 'package:permission_handler/permission_handler.dart';

Future<void> requestSMSPermission() async {
  var status = await Permission.sms.status;
  if (!status.isGranted) {
    await Permission.sms.request();
  }
}

4. 使用 otp_detection_flutter 插件

现在你可以在你的应用中使用 otp_detection_flutter 插件来检测 OTP。

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: OTPDetectionScreen(),
    );
  }
}

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

class _OTPDetectionScreenState extends State<OTPDetectionScreen> {
  String _otp = '';

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

  void _startOTPDetection() async {
    await requestSMSPermission();

    OTPDetectionFlutter.otpStream.listen((otp) {
      setState(() {
        _otp = otp;
      });
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('OTP Detection'),
      ),
      body: Center(
        child: Text('Detected OTP: $_otp'),
      ),
    );
  }
}
回到顶部