Flutter无OTP(一次性密码)验证插件otpless_flutter的使用
Flutter无OTP(一次性密码)验证插件otpless_flutter的使用
OTPLESS Flutter SDK
OTPLESS Flutter SDK允许您在Flutter应用程序中实现无OTP的身份验证流程。这使得用户可以通过其他方式(如电话号码或电子邮件)进行身份验证,而无需手动输入一次性密码。
安装
您可以查看完整的安装指南 here。
作者
示例代码
下面是一个完整的示例demo,展示了如何使用otpless_flutter
插件来实现无OTP的身份验证:
import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:otpless_flutter/otpless_flutter.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _dataResponse = 'Unknown';
final _otplessFlutterPlugin = Otpless();
var loaderVisibility = true;
bool isSimStateListenerAttached = false;
final TextEditingController phoneOrEmailTextController =
TextEditingController();
final TextEditingController otpController = TextEditingController();
String channel = "WHATSAPP";
String phoneOrEmail = '';
String otp = '';
bool isInitIos = false;
String deliveryChannel = '';
String otpLength = "";
String expiry = "";
static const String appId = "YOUR_APPID"; // 替换为您的应用ID
@override
void initState() {
super.initState();
_otplessFlutterPlugin.enableDebugLogging(true);
if (Platform.isAndroid) {
_otplessFlutterPlugin.initHeadless(appId);
_otplessFlutterPlugin.setHeadlessCallback(onHeadlessResult);
debugPrint("init headless sdk is called for android");
attachSecureService();
}
_otplessFlutterPlugin.setWebviewInspectable(true);
}
Future<void> attachSecureService() async {
try {
await _otplessFlutterPlugin.attachSecureService(appId);
} on PlatformException catch (e) {
print(
'PlatformException: ${e.message}, code: ${e.code}, details: ${e.details}');
}
}
Future<void> getEjectedSimStatus() async {
List<Map<String, dynamic>> data =
await _otplessFlutterPlugin.getEjectedSimEntries();
setState(() {
_dataResponse = data.toString();
});
}
Future<void> openLoginPage() async {
Map<String, dynamic> arg = {'appId': appId};
_otplessFlutterPlugin.openLoginPage(onLoginPageResult, arg);
}
Future<void> startHeadlessWithChannel() async {
if (Platform.isIOS && !isInitIos) {
_otplessFlutterPlugin.initHeadless(appId);
_otplessFlutterPlugin.setHeadlessCallback(onHeadlessResult);
isInitIos = true;
debugPrint("init headless sdk is called for ios");
return;
}
Map<String, dynamic> arg = {'channelType': channel};
_otplessFlutterPlugin.startHeadless(onHeadlessResult, arg);
}
Future<void> startHeadlessForPhoneAndEmail() async {
if (Platform.isIOS && !isInitIos) {
_otplessFlutterPlugin.initHeadless(appId);
_otplessFlutterPlugin.setHeadlessCallback(onHeadlessResult);
isInitIos = true;
debugPrint("init headless sdk is called for ios");
return;
}
Map<String, dynamic> arg = {};
var x = double.tryParse(phoneOrEmail);
if (x != null) {
arg["phone"] = phoneOrEmail;
arg["countryCode"] = "91";
} else {
arg["email"] = phoneOrEmail;
}
if (otp.isNotEmpty) {
arg["otp"] = otp;
}
// adding delivery channel, otp length and expiry
if (deliveryChannel.isNotEmpty) {
arg["deliveryChannel"] = deliveryChannel;
}
if (otpLength.isNotEmpty) {
arg["otpLength"] = otpLength;
}
if (expiry.isNotEmpty) {
arg["expiry"] = expiry;
}
_otplessFlutterPlugin.startHeadless(onHeadlessResult, arg);
}
Future<void> onSimCheckboxChange(bool isChecked) async {
if (isChecked) {
_otplessFlutterPlugin.setSimEventListener((data) {
setState(() {
_dataResponse = data.toString();
});
});
} else {
_otplessFlutterPlugin.setSimEventListener(null);
}
}
void onHeadlessResult(dynamic result) {
setState(() {
_dataResponse = jsonEncode(result);
String responseType = result["responseType"];
if (responseType == "OTP_AUTO_READ") {
String _otp = result["response"]["otp"];
otpController.text = _otp;
otp = _otp;
}
});
}
void onLoginPageResult(dynamic result) {
setState(() {
_dataResponse = jsonEncode(result);
});
}
Future<void> changeLoaderVisibility() async {
loaderVisibility = !loaderVisibility;
_otplessFlutterPlugin.setLoaderVisibility(loaderVisibility);
}
@override
void dispose() {
phoneOrEmailTextController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('OTPless Flutter Plugin example app'),
),
body: SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16.0), // Adjusted margin
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment
.stretch, // Makes the buttons fill the width
children: [
CupertinoButton.filled(
onPressed: openLoginPage,
child: const Text("Open Otpless Login Page"),
),
const SizedBox(height: 16), // Spacing between buttons
CupertinoButton.filled(
onPressed: changeLoaderVisibility,
child: const Text("Toggle Loader Visibility"),
),
const SizedBox(height: 16),
CupertinoButton.filled(
onPressed: startHeadlessWithChannel,
child: const Text("Start Headless With Channel"),
),
const SizedBox(height: 16),
CupertinoButton.filled(
onPressed: handlePhoneHint,
child: const Text("Show Phone Hint")),
const SizedBox(height: 16),
CupertinoButton.filled(
onPressed: getEjectedSimStatus,
child: const Text("Sim Eject Status")),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Checkbox(
value: isSimStateListenerAttached,
onChanged: (bool? value) {
onSimCheckboxChange(value ?? false);
setState(() {
isSimStateListenerAttached = value!;
});
},
),
Text(
isSimStateListenerAttached
? 'Remove Sim Change Listener'
: 'Attach Sim Change Listener',
style: TextStyle(fontSize: 20),
),
]),
TextField(
controller: phoneOrEmailTextController,
onChanged: (value) {
setState(() {
phoneOrEmail = value;
});
},
decoration: const InputDecoration(
hintText: 'Enter Phone or email here',
),
),
const SizedBox(height: 16),
TextField(
controller: otpController,
onChanged: (value) {
setState(() {
otp = value;
});
},
decoration: const InputDecoration(
hintText: 'Enter your OTP here',
),
),
const SizedBox(height: 16),
TextField(
onChanged: (value) {
setState(() {
channel = value;
});
},
decoration: const InputDecoration(
hintText: 'Enter channel',
),
),
const SizedBox(height: 16),
CupertinoButton.filled(
onPressed: startHeadlessForPhoneAndEmail,
child: const Text("Start with Phone and Email"),
),
const SizedBox(height: 16),
// adding delivery channel
TextField(
onChanged: (value) {
deliveryChannel = value;
},
decoration: const InputDecoration(
hintText: "Enter Delivery Channel"),
),
const SizedBox(height: 16),
// adding otp length
TextField(
onChanged: (value) {
otpLength = value;
},
decoration:
const InputDecoration(hintText: "Enter the OTP length"),
keyboardType: TextInputType.number,
),
const SizedBox(height: 16),
// adding expiry
TextField(
onChanged: (value) {
expiry = value;
},
decoration: const InputDecoration(
hintText: "Enter the expiry in seconds"),
keyboardType: TextInputType.number,
),
const SizedBox(height: 16),
// response view
Text(
_dataResponse,
textAlign: TextAlign.center,
),
],
),
),
),
)),
),
);
}
void handlePhoneHint() async {
final result = await _otplessFlutterPlugin.showPhoneHint(true);
setState(() {
if (result["phoneNumber"] != null) {
String phone = result["phoneNumber"]!;
if (phone.length > 10) {
phone = phone.substring(phone.length - 10);
}
phoneOrEmail = phone;
phoneOrEmailTextController.text = phoneOrEmail;
} else {
_dataResponse = result["error"]!;
}
});
}
}
关键点解释
-
初始化:
initHeadless(appId)
:初始化后台服务。setHeadlessCallback(onHeadlessResult)
:设置回调函数以处理后台结果。
-
启动无头模式:
startHeadless(onHeadlessResult, arg)
:根据提供的参数启动后台验证流程。
-
显示登录页面:
openLoginPage(onLoginPageResult, arg)
:打开登录页面并处理返回的结果。
-
处理SIM卡状态变化:
setSimEventListener
:监听SIM卡状态变化。
-
显示电话提示:
showPhoneHint(true)
:获取用户的电话号码提示。
-
UI交互:
- 提供多个按钮和文本框,用于触发不同的验证流程,并显示响应结果。
注意事项
- 确保替换
YOUR_APPID
为您的实际应用ID。 - 根据需要调整渠道、OTP长度和过期时间等参数。
通过以上步骤,您可以轻松地在Flutter应用程序中集成无OTP的身份验证功能。希望这个示例能帮助您更好地理解和使用otpless_flutter
插件。
更多关于Flutter无OTP(一次性密码)验证插件otpless_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter无OTP(一次性密码)验证插件otpless_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中集成和使用otpless_flutter
插件的示例代码。otpless_flutter
插件允许你实现无OTP(一次性密码)的验证流程,通常用于短信或邮件验证码的替代方案。
首先,你需要在你的pubspec.yaml
文件中添加otpless_flutter
依赖:
dependencies:
flutter:
sdk: flutter
otpless_flutter: ^最新版本号 # 请替换为实际最新版本号
然后运行flutter pub get
来安装依赖。
接下来,我们将展示如何在Flutter应用中使用otpless_flutter
进行无OTP验证。以下是一个简单的示例,包括初始化、启动验证和处理回调。
import 'package:flutter/material.dart';
import 'package:otpless_flutter/otpless_flutter.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter OTPless Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: OtplessDemoScreen(),
);
}
}
class OtplessDemoScreen extends StatefulWidget {
@override
_OtplessDemoScreenState createState() => _OtplessDemoScreenState();
}
class _OtplessDemoScreenState extends State<OtplessDemoScreen> {
final Otpless _otpless = Otpless();
@override
void initState() {
super.initState();
// 初始化 Otpless
_initializeOtpless();
}
Future<void> _initializeOtpless() async {
try {
// 替换为你的实际后端 URL
String backendUrl = 'https://your-backend-url.com/otpless';
await _otpless.initialize(
serverUrl: backendUrl,
// 如果需要自定义用户代理,可以传递 userAgent 参数
// userAgent: 'Your-User-Agent',
);
print('Otpless initialized successfully');
} catch (e) {
print('Failed to initialize Otpless: $e');
}
}
Future<void> _startVerification() async {
try {
// 替换为你的用户 ID 或其他唯一标识符
String userId = 'user-12345';
String phoneNumber = '+1234567890'; // 用户电话号码
// 启动验证流程
OtplessVerificationResult result = await _otpless.startVerification(
userId: userId,
phoneNumber: phoneNumber,
// 如果需要自定义通道(例如 SMS、EMAIL),可以传递 channel 参数
// channel: OtplessChannel.sms,
);
if (result.success) {
print('Verification started successfully');
} else {
print('Failed to start verification: ${result.error}');
}
} catch (e) {
print('Error during verification: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter OTPless Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _startVerification,
child: Text('Start Verification'),
),
],
),
),
);
}
}
注意事项:
- 后端集成:
otpless_flutter
需要与你的后端服务进行集成。后端服务需要处理验证请求并返回相应的响应。确保你的后端URL和验证逻辑正确配置。 - 用户ID和电话号码:在调用
startVerification
方法时,需要提供用户ID和电话号码。这些值应根据你的应用逻辑进行替换。 - 错误处理:示例代码包含基本的错误处理逻辑,但在实际应用中,你可能需要更详细的错误处理和用户反馈。
依赖配置
确保你的后端服务已经按照otpless
文档进行了配置,并且你的Flutter应用具有访问该服务的必要权限(例如网络权限)。
这样,你就可以在Flutter应用中集成并使用otpless_flutter
插件来实现无OTP验证了。