Flutter电话与邮箱认证插件phone_email_auth的使用
Flutter电话与邮箱认证插件phone_email_auth的使用
Getting Started(开始)
安装
dependencies:
phone_email_auth: ^0.0.6
导入
import 'package:phone_email_auth/phone_email_auth.dart';
初始化插件
PhoneEmail.initializeApp(clientId: 'YOUR_CLIENT_ID');
注意:clientId
是你在 Phone Email 的 Admin Dashboard 的 Profile Details 部分获得的。
添加电话与邮箱登录按钮
child: PhoneLoginButton(
borderRadius: 8,
buttonColor: Colors.teal,
label: 'Sign in with Phone',
onSuccess: (String accessToken, String jwtToken) {
if (accessToken.isNotEmpty) {
setState(() {
userAccessToken = accessToken;
jwtUserToken = jwtToken;
hasUserLogin = true;
});
}
},
)
PhoneLoginButton 将返回 accessToken
和 jwtToken
,这些是获取验证手机号码所必需的。
获取验证后的手机号码
一旦你获得了 accessToken
,你可以通过调用 getUserInfo()
函数来获取验证后的手机号码。使用以下代码片段来检索验证后的手机号码和用户详情。
PhoneEmail.getUserInfo(
accessToken: userAccessToken,
clientId: phoneEmail.clientId,
onSuccess: (userData) {
setState(() {
phoneEmailUserModel = userData;
var countryCode = phoneEmailUserModel?.countryCode;
var phoneNumber = phoneEmailUserModel?.phoneNumber;
var firstName = phoneEmailUserModel?.firstName;
var lastName = phoneEmailUserModel?.lastName;
// 使用此验证后的手机号码来注册用户并创建会话
});
},
);
显示邮箱提醒
为已成功认证的用户集成一个邮箱提醒图标。使用以下代码片段来获取未读邮件数量并显示邮箱图标。
floatingActionButton: hasUserLogin
? EmailAlertButton(
jwtToken: jwtUserToken,
) : const Offstage(),
完整示例代码
import 'package:flutter/material.dart';
import 'package:phone_email_auth/phone_email_auth.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
/// 初始化电话电子邮件功能
PhoneEmail.initializeApp(clientId: 'YOUR_CLIENT_ID');
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
[@override](/user/override)
void initState() {
super.initState();
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Phone Email',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: const Color.fromARGB(255, 4, 201, 135),
),
useMaterial3: true,
),
home: const PhoneEmailAuthWidget(),
);
}
}
class PhoneEmailAuthWidget extends StatefulWidget {
const PhoneEmailAuthWidget({super.key});
[@override](/user/override)
State<PhoneEmailAuthWidget> createState() => _PhoneEmailAuthWidgetState();
}
class _PhoneEmailAuthWidgetState extends State<PhoneEmailAuthWidget> {
String userAccessToken = "";
String jwtUserToken = "";
bool hasUserLogin = false;
PhoneEmailUserModel? phoneEmailUserModel;
final phoneEmail = PhoneEmail();
String emailCount = '';
/// 获取邮件总数
void getTotalEmailCount() async {
await PhoneEmail.getEmailCount(
jwtUserToken,
onEmailCount: (count) {
setState(() {
emailCount = count;
});
},
);
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: const Text('Phone Email'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (hasUserLogin) ...[
if (phoneEmailUserModel != null) ...[
Divider(
thickness: 0.5,
color: Colors.grey.shade400,
),
const SizedBox(height: 16.0),
const Text(
"User Data",
style: TextStyle(
fontSize: 22,
color: Colors.black,
),
),
const SizedBox(height: 16.0),
Text(
"User name : ${phoneEmailUserModel?.firstName} ${phoneEmailUserModel?.lastName}",
style: const TextStyle(
fontSize: 16,
color: Colors.black,
),
),
const SizedBox(height: 16.0),
Text(
"Phone Number : ${phoneEmailUserModel?.countryCode} ${phoneEmailUserModel?.phoneNumber}",
style: const TextStyle(
fontSize: 16,
color: Colors.black,
),
),
const SizedBox(height: 16.0),
],
if (emailCount.isNotEmpty) ...[
Divider(
thickness: 0.5,
color: Colors.grey.shade400,
),
const SizedBox(height: 16.0),
Text(
"Email Count : $emailCount",
style: const TextStyle(
fontSize: 16,
color: Colors.black,
),
),
const SizedBox(height: 16.0),
],
],
/// 默认按钮
if (!hasUserLogin) ...[
/// 带有额外圆角的按钮
/// 背景颜色不同
/// 不同的文字
Align(
alignment: Alignment.center,
child: PhoneLoginButton(
borderRadius: 15,
buttonColor: Colors.green,
label: 'Sign in with Number',
onSuccess: (String accessToken, String jwtToken) {
if (accessToken.isNotEmpty) {
setState(() {
userAccessToken = accessToken;
jwtUserToken = jwtToken;
hasUserLogin = true;
});
PhoneEmail.getUserInfo(
accessToken: userAccessToken,
clientId: phoneEmail.clientId,
onSuccess: (userData) {
setState(() {
phoneEmailUserModel = userData;
var countryCode = phoneEmailUserModel?.countryCode;
var phoneNumber = phoneEmailUserModel?.phoneNumber;
var firstName = phoneEmailUserModel?.firstName;
var lastName = phoneEmailUserModel?.lastName;
debugPrint("countryCode :: $countryCode");
debugPrint("phoneNumber :: $phoneNumber");
debugPrint("firstName :: $firstName");
debugPrint("lastName :: $lastName");
getTotalEmailCount();
});
},
);
}
},
),
),
],
const SizedBox(height: 16.0),
/// 登出
Align(
alignment: Alignment.center,
child: ElevatedButton(
onPressed: () {
hasUserLogin = false;
userAccessToken = "";
jwtUserToken = "";
phoneEmailUserModel = null;
emailCount = '0';
setState(() {});
},
child: const Text("Logout"),
),
),
],
),
),
/// 邮箱按钮
floatingActionButtonLocation: FloatingActionButtonLocation.startFloat,
floatingActionButton: hasUserLogin
? EmailAlertButton(
jwtToken: jwtUserToken,
)
: const Offstage(),
);
}
}
更多关于Flutter电话与邮箱认证插件phone_email_auth的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter电话与邮箱认证插件phone_email_auth的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何使用 phone_email_auth
插件在 Flutter 中实现电话与邮箱认证的代码示例。请确保你已经添加了 phone_email_auth
依赖到你的 pubspec.yaml
文件中,并且已经运行了 flutter pub get
。
首先,你的 pubspec.yaml
文件应该包含以下依赖:
dependencies:
flutter:
sdk: flutter
phone_email_auth: ^最新版本号 # 请替换为实际的最新版本号
然后,你可以按照以下步骤在你的 Flutter 应用中实现电话与邮箱认证。
1. 导入插件
在你的 Dart 文件中导入 phone_email_auth
插件:
import 'package:phone_email_auth/phone_email_auth.dart';
2. 初始化 Firebase
在使用 phone_email_auth
之前,你需要确保已经正确初始化了 Firebase。这通常是在你的应用的 main.dart
文件中完成的。
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:phone_email_auth/phone_email_auth.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
3. 实现电话认证
下面是一个使用电话号码进行认证的例子:
class PhoneAuthScreen extends StatefulWidget {
@override
_PhoneAuthScreenState createState() => _PhoneAuthScreenState();
}
class _PhoneAuthScreenState extends State<PhoneAuthScreen> {
final PhoneEmailAuth _auth = PhoneEmailAuth.instance;
String _verificationId;
String _smsCode;
String _phoneNumber = "+1234567890"; // 示例电话号码
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Phone Authentication'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
decoration: InputDecoration(labelText: 'Phone Number'),
keyboardType: TextInputType.phone,
onChanged: (value) {
_phoneNumber = value;
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
try {
_verificationId = await _auth.verifyPhoneNumber(
phoneNumber: _phoneNumber,
verificationCompleted: (AuthCredential phoneAuthCredential) {
// 用户自动验证完成,例如即时消息回调
// 你可以在这里登录用户
},
verificationFailed: (FirebaseAuthException e) {
// 显示一些错误消息
},
codeSent: (String verificationId, [int forceResendingToken]) async {
// 保存 verificationId 以便后续使用
this._verificationId = verificationId;
// 提示用户输入验证码
},
codeAutoRetrievalTimeout: (String verificationId) {
// 自动检索验证码超时
this._verificationId = verificationId;
},
);
} catch (e) {
print(e);
}
},
child: Text('Send Verification Code'),
),
SizedBox(height: 20),
TextField(
decoration: InputDecoration(labelText: 'SMS Code'),
keyboardType: TextInputType.number,
onChanged: (value) {
_smsCode = value;
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
if (_verificationId != null && _smsCode != null) {
try {
final AuthCredential credential = PhoneAuthProvider.credential(
verificationId: _verificationId,
smsCode: _smsCode,
);
// 使用凭证登录
await FirebaseAuth.instance.signInWithCredential(credential);
// 登录成功后的逻辑
} catch (e) {
print(e);
}
}
},
child: Text('Verify Code'),
),
],
),
),
);
}
}
4. 实现邮箱认证
下面是一个使用邮箱进行认证的例子:
class EmailAuthScreen extends StatefulWidget {
@override
_EmailAuthScreenState createState() => _EmailAuthScreenState();
}
class _EmailAuthScreenState extends State<EmailAuthScreen> {
final FirebaseAuth _auth = FirebaseAuth.instance;
String _email = "example@example.com";
String _password = "password123";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Email Authentication'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
decoration: InputDecoration(labelText: 'Email'),
keyboardType: TextInputType.emailAddress,
onChanged: (value) {
_email = value;
},
),
SizedBox(height: 20),
TextField(
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
onChanged: (value) {
_password = value;
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
try {
UserCredential result = await _auth.createUserWithEmailAndPassword(
email: _email,
password: _password,
);
User? user = result.user;
// 用户创建成功后的逻辑
} catch (e) {
print(e);
}
},
child: Text('Sign Up'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
try {
UserCredential result = await _auth.signInWithEmailAndPassword(
email: _email,
password: _password,
);
User? user = result.user;
// 用户登录成功后的逻辑
} catch (e) {
print(e);
}
},
child: Text('Sign In'),
),
],
),
),
);
}
}
以上代码展示了如何使用 phone_email_auth
插件在 Flutter 应用中实现电话和邮箱认证。请注意,实际开发中你需要处理更多的边缘情况和错误处理,以确保用户体验的流畅性和安全性。