Flutter自动获取OTP插件auto_otp的使用

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

Flutter自动获取OTP插件auto_otp的使用

auto_otp 是一个用于Android设备的Flutter插件,可以通过Sms Retriever API自动读取短信。

开始使用

以下是如何在你的Flutter项目中使用auto_otp插件的示例:

import 'dart:async';

import 'package:auto_otp/auto_otp.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _sms = 'Unknown';
  final _autoOtpPlugin = AutoOtp();

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

  [@override](/user/override)
  void dispose() {
    _autoOtpPlugin.removeSmsListener();
    super.dispose();
  }

  // 平台消息是异步的,因此我们通过异步方法初始化。
  Future<void> initPlatformState() async {
    String platformVersion;
    // 平台消息可能会失败,所以我们使用try/catch处理PlatformException。
    // 我们还处理了消息可能返回null的情况。
    try {
      platformVersion = await _autoOtpPlugin.getSmsCode() ?? '无法捕获短信';
    } on PlatformException {
      platformVersion = '获取短信失败';
    }

    // 如果小部件从树中被移除而异步平台消息仍在飞行中,我们希望丢弃回复而不是调用setState来更新我们的非存在的外观。
    if (!mounted) return;

    setState(() {
      _sms = platformVersion;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('自动OTP应用')),
        body: Center(child: Text('短信状态: $_sms')),
      ),
    );
  }
}

功能优势

  • 无需额外权限请求:使用该插件时,你无需为应用添加任何额外的权限。
  • 无需用户手动输入OTP:插件会自动读取短信中的OTP,从而简化用户体验。

完整示例代码

以下是完整的示例代码,展示了如何在Flutter项目中集成和使用auto_otp插件:

import 'dart:async';

import 'package:auto_otp/auto_otp.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _sms = 'Unknown';
  final _autoOtpPlugin = AutoOtp();

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

  [@override](/user/override)
  void dispose() {
    _autoOtpPlugin.removeSmsListener();
    super.dispose();
  }

  // 平台消息是异步的,因此我们通过异步方法初始化。
  Future<void> initPlatformState() async {
    String platformVersion;
    // 平台消息可能会失败,所以我们使用try/catch处理PlatformException。
    // 我们还处理了消息可能返回null的情况。
    try {
      platformVersion = await _autoOtpPlugin.getSmsCode() ?? '无法捕获短信';
    } on PlatformException {
      platformVersion = '获取短信失败';
    }

    // 如果小部件从树中被移除而异步平台消息仍在飞行中,我们希望丢弃回复而不是调用setState来更新我们的非存在的外观。
    if (!mounted) return;

    setState(() {
      _sms = platformVersion;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('自动OTP应用')),
        body: Center(child: Text('短信状态: $_sms')),
      ),
    );
  }
}

更多关于Flutter自动获取OTP插件auto_otp的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter自动获取OTP插件auto_otp的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter应用中使用auto_otp插件来自动获取和处理一次性密码(OTP)的代码示例。这个插件通常用于处理短信中的OTP,并允许应用程序自动读取和填充OTP。

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

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

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

接下来,你可以在你的Flutter应用中按如下方式使用auto_otp插件:

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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String? otp;
  bool isListening = false;

  @override
  void initState() {
    super.initState();
    initAutoOtp();
  }

  @override
  void dispose() {
    if (isListening) {
      AutoOtp.stopListeningSms();
    }
    super.dispose();
  }

  Future<void> initAutoOtp() async {
    // 请求权限以读取短信
    bool hasPermission = await AutoOtp.requestSmsPermission();
    if (hasPermission) {
      // 开始监听短信中的OTP
      AutoOtp.startListeningSms().then((_) {
        setState(() {
          isListening = true;
        });
      });

      // 监听OTP获取事件
      AutoOtp.otpStream.listen((otpMessage) {
        setState(() {
          otp = otpMessage?.message;
        });
      });
    } else {
      print("SMS Permission Denied");
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Auto OTP Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'OTP:',
                style: TextStyle(fontSize: 20),
              ),
              SizedBox(height: 10),
              Text(
                otp ?? 'Waiting for OTP...',
                style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: isListening ? () async {
                  await AutoOtp.stopListeningSms();
                  setState(() {
                    isListening = false;
                  });
                } : null,
                child: Text(isListening ? 'Stop Listening' : 'Start Listening'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

解释:

  1. 依赖导入:在pubspec.yaml中添加auto_otp依赖。
  2. 请求权限:在initAutoOtp方法中,使用AutoOtp.requestSmsPermission()请求读取短信的权限。
  3. 开始监听:使用AutoOtp.startListeningSms()开始监听短信。如果监听成功,设置isListeningtrue
  4. 监听OTP流:使用AutoOtp.otpStream.listen()监听OTP消息。一旦收到OTP消息,更新UI中的otp变量。
  5. UI更新:在UI中显示OTP,并提供一个按钮来启动或停止监听短信。

请注意,在实际应用中,你需要处理更多的错误场景,例如权限被拒绝、监听失败等。此外,根据auto_otp插件的具体实现和版本,API可能会有所不同,因此请查阅最新的文档和示例代码。

回到顶部