百度一下百度主页官网,西安网站建设优化服务公司,跨境o2o网站建设方案,丹东seo排名公司Flutter-OH SMS Autofill 插件完整使用教程
一、插件介绍
一直以来#xff0c;大家在Flutter开发鸿蒙应用的过程中#xff0c;其中一个热点就是三方库的使用#xff0c;
今天我们来看一下如何在鸿蒙平台上使用sms_autofill
sms_autofill 是一个强大的 Flutter 插件…Flutter-OH SMS Autofill 插件完整使用教程一、插件介绍一直以来大家在Flutter开发鸿蒙应用的过程中其中一个热点就是三方库的使用今天我们来看一下如何在鸿蒙平台上使用sms_autofillsms_autofill是一个强大的 Flutter 插件用于自动读取和填充短信验证码OTP。它支持 Android 和 iOS 平台能够自动监听短信并提取验证码大大提升用户体验。主要特性✅自动读取短信验证码无需手动输入自动识别并填充验证码✅多种输入组件提供PinFieldAutoFill、TextFieldPinAutoFill等多种样式✅应用签名支持Android 平台支持应用签名验证确保安全性✅Mixin 支持提供CodeAutoFillmixin简化代码实现✅跨平台支持同时支持 Android 和 iOS适用场景用户登录/注册时的短信验证码输入密码重置验证支付确认验证任何需要短信验证码的场景二、安装步骤2.1 添加依赖在项目的pubspec.yaml文件中添加sms_autofill依赖dependencies: flutter: sdk: flutter sms_autofill: ^2.4.12.2 安装包在终端中运行以下命令安装依赖flutter pub get安装完成后你会看到类似以下的输出Resolving dependencies... pin_input_text_field 4.5.2 sms_autofill 2.4.1 Changed 2 dependencies!三、平台配置3.1 Android 配置步骤 1添加权限在android/app/src/main/AndroidManifest.xml文件中添加短信读取权限manifest xmlns:androidhttp://schemas.android.com/apk/res/android !-- 添加短信读取权限 -- uses-permission android:nameandroid.permission.RECEIVE_SMS/ uses-permission android:nameandroid.permission.READ_SMS/ application !-- 其他配置 -- /application /manifest步骤 2运行时权限申请在 Android 6.0 (API 23) 及以上版本需要在运行时动态申请权限。可以使用permission_handler插件dependencies: permission_handler: ^11.0.0步骤 3获取应用签名可选但推荐Android 的 SMS Retriever API 需要应用签名来验证短信来源。获取应用签名的方法方法一使用插件提供的 APIString signature await SmsAutoFill().getAppSignature; print(App Signature: $signature);方法二使用命令行工具# 对于 debug 版本 keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -storepass android -keypass android | xxd -p | tr -d [:space:] | echo -n com.example.app $(cat) | sha256sum | tr -d [:space:]- | xxd -r -p | base64 | cut -c1-11 # 对于 release 版本 keytool -exportcert -alias your-key-alias -keystore path/to/your/keystore.jks | xxd -p | tr -d [:space:] | echo -n com.example.app $(cat) | sha256sum | tr -d [:space:]- | xxd -r -p | base64 | cut -c1-11方法三使用在线工具访问 Google Play Console 或使用其他在线签名工具。3.2 iOS 配置步骤 1添加权限说明在ios/Runner/Info.plist文件中添加短信权限说明keyNSUserTrackingUsageDescription/key string我们需要访问您的短信以自动填充验证码/string步骤 2启用短信自动填充iOS 的短信自动填充功能需要满足以下条件短信格式必须符合特定规范短信必须来自可信来源应用需要正确配置 Associated Domains可选短信格式示例您的验证码是123456请在5分钟内使用。【应用名称】或者使用标准格式# 您的验证码是123456 ABC123XYZ其中ABC123XYZ是应用签名哈希。四、基本使用4.1 导入包在需要使用短信自动填充功能的文件中导入import package:sms_autofill/sms_autofill.dart;4.2 使用 PinFieldAutoFill推荐PinFieldAutoFill是一个专门用于验证码输入的组件支持多种装饰样式class VerificationPage extends StatefulWidget { override _VerificationPageState createState() _VerificationPageState(); } class _VerificationPageState extends StateVerificationPage { String _code ; override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(验证码输入)), body: Padding( padding: EdgeInsets.all(16.0), child: Column( children: [ // 下划线样式 PinFieldAutoFill( decoration: UnderlineDecoration( textStyle: TextStyle(fontSize: 20, color: Colors.black), colorBuilder: FixedColorBuilder(Colors.black.withOpacity(0.3)), ), currentCode: _code, codeLength: 6, // 验证码长度 onCodeSubmitted: (code) { // 验证码提交时的回调 print(验证码: $code); // 这里可以调用验证接口 }, onCodeChanged: (code) { setState(() { _code code ?? ; }); // 当输入完成时自动提交 if (code ! null code.length 6) { // 自动提交或隐藏键盘 FocusScope.of(context).unfocus(); } }, ), ], ), ), ); } override void dispose() { SmsAutoFill().unregisterListener(); super.dispose(); } }装饰样式选项1. 下划线样式UnderlineDecorationPinFieldAutoFill( decoration: UnderlineDecoration( textStyle: TextStyle(fontSize: 20, color: Colors.black), colorBuilder: FixedColorBuilder(Colors.black.withOpacity(0.3)), ), // ... )2. 方框样式BoxLooseDecorationPinFieldAutoFill( decoration: BoxLooseDecoration( strokeColor: Colors.blue, bgColorBuilder: FixedColorBuilder(Colors.grey.withOpacity(0.1)), textStyle: TextStyle(fontSize: 20, color: Colors.black), ), // ... )3. 圆角方框样式BoxTightDecorationPinFieldAutoFill( decoration: BoxTightDecoration( strokeColor: Colors.blue, radius: Radius.circular(8), textStyle: TextStyle(fontSize: 20, color: Colors.black), ), // ... )4.3 使用 TextFieldPinAutoFill如果你更喜欢使用标准的TextField可以使用TextFieldPinAutoFillTextFieldPinAutoFill( currentCode: _code, onCodeSubmitted: (code) { print(验证码: $code); }, decoration: InputDecoration( labelText: 请输入验证码, border: OutlineInputBorder(), ), )4.4 手动监听短信如果需要手动控制短信监听// 开始监听 await SmsAutoFill().listenForCode(); // 停止监听 SmsAutoFill().unregisterListener();4.5 获取应用签名String signature await SmsAutoFill().getAppSignature; print(App Signature: $signature);五、高级功能5.1 使用 CodeAutoFill MixinCodeAutoFillmixin 提供了更简洁的方式来处理短信验证码class VerificationPage extends StatefulWidget { override _VerificationPageState createState() _VerificationPageState(); } class _VerificationPageState extends StateVerificationPage with CodeAutoFill { String? appSignature; String? otpCode; override void codeUpdated() { // 当收到验证码时自动调用 setState(() { otpCode code; }); // 可以在这里自动提交验证码 if (code ! null code!.length 6) { _verifyCode(code!); } } override void initState() { super.initState(); // 开始监听 listenForCode(); // 获取应用签名 SmsAutoFill().getAppSignature.then((signature) { setState(() { appSignature signature; }); }); } override void dispose() { // 取消监听 cancel(); super.dispose(); } void _verifyCode(String code) { // 验证验证码的逻辑 print(验证码: $code); } override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(验证码验证)), body: Column( children: [ if (otpCode ! null) Text(收到的验证码: $otpCode), if (appSignature ! null) Text(应用签名: $appSignature), ], ), ); } }5.2 显示手机号提示PhoneFieldHint组件可以显示用户的手机号帮助用户确认PhoneFieldHint( child: Text(我们将向 86 138****8888 发送验证码), )5.3 自定义验证码格式如果需要自定义验证码的提取规则可以使用正则表达式// 在监听时指定验证码格式 await SmsAutoFill().listenForCode( codeLength: 6, // 可以添加自定义的验证码提取逻辑 );六、完整示例代码以下是一个完整的短信验证码输入页面示例import package:flutter/material.dart; import package:sms_autofill/sms_autofill.dart; void main() runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData.light(), home: const HomePage(), ); } } class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); override StateHomePage createState() _HomePageState(); } class _HomePageState extends StateHomePage { String _code ; String signature {{ app signature }}; override void initState() { super.initState(); } override void dispose() { SmsAutoFill().unregisterListener(); super.dispose(); } override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text(短信验证码示例), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, children: Widget[ // 手机号提示 const PhoneFieldHint(), const SizedBox(height: 32), // 下划线样式的验证码输入框 const Text( 验证码输入下划线样式, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), const SizedBox(height: 16), PinFieldAutoFill( decoration: UnderlineDecoration( textStyle: const TextStyle(fontSize: 20, color: Colors.black), colorBuilder: FixedColorBuilder(Colors.black.withOpacity(0.3)), ), currentCode: _code, codeLength: 6, onCodeSubmitted: (code) { _handleCodeSubmitted(code); }, onCodeChanged: (code) { setState(() { _code code ?? ; }); if (code ! null code.length 6) { FocusScope.of(context).requestFocus(FocusNode()); } }, ), const SizedBox(height: 32), // 文本输入框样式的验证码输入 const Text( 验证码输入文本输入框样式, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), const SizedBox(height: 16), TextFieldPinAutoFill( currentCode: _code, onCodeSubmitted: (code) { _handleCodeSubmitted(code); }, ), const Spacer(), // 操作按钮 ElevatedButton( child: const Text(开始监听短信验证码), onPressed: () async { await SmsAutoFill().listenForCode(); ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text(已开始监听短信验证码)), ); }, ), const SizedBox(height: 8), ElevatedButton( child: const Text(获取应用签名), onPressed: () async { signature await SmsAutoFill().getAppSignature; setState(() {}); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(应用签名: $signature)), ); }, ), const SizedBox(height: 8), Text(应用签名: $signature), const SizedBox(height: 16), ElevatedButton( onPressed: () { Navigator.of(context).push( MaterialPageRoute( builder: (_) const CodeAutoFillTestPage(), ), ); }, child: const Text(使用 CodeAutoFill Mixin 示例), ), ], ), ), ); } void _handleCodeSubmitted(String code) { print(提交的验证码: $code); // 这里可以调用验证接口 ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(验证码: $code)), ); } } // 使用 CodeAutoFill Mixin 的示例页面 class CodeAutoFillTestPage extends StatefulWidget { const CodeAutoFillTestPage({Key? key}) : super(key: key); override StateCodeAutoFillTestPage createState() _CodeAutoFillTestPageState(); } class _CodeAutoFillTestPageState extends StateCodeAutoFillTestPage with CodeAutoFill { String? appSignature; String? otpCode; override void codeUpdated() { setState(() { otpCode code; }); if (code ! null code!.length 6) { _verifyCode(code!); } } override void initState() { super.initState(); listenForCode(); SmsAutoFill().getAppSignature.then((signature) { setState(() { appSignature signature; }); }); } override void dispose() { super.dispose(); cancel(); } void _verifyCode(String code) { print(验证码: $code); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(收到验证码: $code)), ); } override Widget build(BuildContext context) { const textStyle TextStyle(fontSize: 18); return Scaffold( appBar: AppBar( title: const Text(CodeAutoFill Mixin 示例), ), body: Column( crossAxisAlignment: CrossAxisAlignment.center, children: Widget[ Padding( padding: const EdgeInsets.fromLTRB(32, 32, 32, 0), child: Text( 应用签名: ${appSignature ?? 获取中...}, style: textStyle, ), ), const Spacer(), Padding( padding: const EdgeInsets.symmetric(horizontal: 32), child: Builder( builder: (_) { if (otpCode null) { return const Text(正在监听验证码..., style: textStyle); } return Text(收到的验证码: $otpCode, style: textStyle); }, ), ), const Spacer(), ], ), ); } }七、常见问题与解决方案7.1 Android 平台问题问题 1无法自动读取验证码解决方案确保已添加短信读取权限检查应用签名是否正确配置确保短信格式符合 SMS Retriever API 的要求验证码短信必须包含应用签名哈希问题 2应用签名获取失败解决方案确保应用已经签名debug 或 release使用正确的 keystore 文件检查包名是否正确问题 3权限被拒绝解决方案在运行时动态申请权限引导用户到设置页面手动开启权限使用permission_handler插件管理权限7.2 iOS 平台问题问题 1iOS 无法自动填充解决方案确保短信格式正确短信必须来自可信来源检查是否启用了短信自动填充功能设置 信息 验证码自动填充问题 2验证码格式不匹配解决方案确保短信中的验证码格式清晰使用标准的验证码格式如6位数字避免在验证码前后添加特殊字符7.3 通用问题问题 1监听器未正确释放解决方案确保在dispose()方法中调用unregisterListener()或cancel()使用CodeAutoFillmixin 时确保调用cancel()问题 2验证码输入框不显示解决方案检查是否正确导入了包确保currentCode参数已初始化检查装饰样式配置是否正确问题 3验证码自动填充延迟解决方案这是正常现象短信接收和解析需要时间通常延迟在 1-3 秒内可以添加加载提示提升用户体验八、最佳实践8.1 用户体验优化提供手动输入选项即使有自动填充也要允许用户手动输入显示倒计时验证码通常有时效性显示倒计时提醒用户错误提示验证码错误时给出清晰的提示重发验证码提供重新发送验证码的功能8.2 安全性考虑验证码有效期设置合理的验证码有效期通常 5-10 分钟验证码格式使用足够复杂的验证码推荐 6 位数字防暴力破解限制验证码尝试次数应用签名验证Android 平台务必使用应用签名验证8.3 性能优化及时释放资源在页面销毁时及时释放监听器避免重复监听不要同时创建多个监听器合理使用 Mixin使用CodeAutoFillmixin 简化代码总结sms_autofill插件为 Flutter 应用提供了强大的短信验证码自动填充功能。通过本教程你应该能够✅ 正确安装和配置插件✅ 使用各种输入组件✅ 实现短信自动监听和填充✅ 处理常见问题和异常情况✅ 优化用户体验和安全性关键要点平台配置很重要Android 需要权限和签名iOS 需要正确的短信格式资源管理记得在dispose()中释放监听器用户体验提供手动输入选项不要完全依赖自动填充安全性使用应用签名验证设置合理的验证码有效期下一步查看 官方文档探索更多自定义选项集成到你的实际项目中欢迎大家加入开源鸿蒙跨平台开发者社区汇聚全球开发者提供清晰的贡献路径与激励体系你的每一行代码都可能成为产业升级的基石