Flutter Firebase认证插件firebase_auth_rest_2的使用
Flutter Firebase认证插件firebase_auth_rest_2的使用
firebase_auth_rest
一个基于REST的Firebase认证API的纯Dart/Flutter包装器。
特性
- 纯Dart实现
- 在支持dart的所有平台上工作
- 使用官方REST-API端点
- 提供高级类来管理认证和用户
- 支持多个用户同时登录
- 支持自动后台刷新
- 支持所有登录方法
- 提供低级REST类以直接访问API(导入
firebase_auth_rest_2/rest.dart
)
安装
只需将firebase_auth_rest
添加到您的pubspec.yaml
文件中并运行pub get
(或flutter pub get
)。
dependencies:
firebase_auth_rest_2: ^版本号
使用
库的核心有两个主要类:FirebaseAuth
和FirebaseAccount
。您可以使用FirebaseAuth
类执行与特定用户无关的全局API操作,例如创建账户、用户登录,以及重置忘记的密码等功能。
FirebaseAuth
的登录/注册方法会为您提供一个FirebaseAccount
实例。该实例保存用户的认证数据,如ID令牌,并可用于执行各种账户相关的操作,例如更改用户的电子邮件地址或获取完整的用户档案。它还会在接近超时之前自动刷新用户的凭据——尽管可以禁用此功能并手动执行。
以下是一个简单的示例,完整的代码包括错误处理可以在https://pub.dev/packages/firebase_auth_rest_2/example找到。该示例以匿名用户登录,打印凭证和账户详细信息,然后永久删除账户。
// 创建认证实例并以匿名用户登录
final fbAuth = FirebaseAuth(Client(), "API-KEY", 'en-US');
final account = await fbAuth.signUpAnonymous(autoRefresh: false);
// 打印本地ID和ID令牌
print("Local-ID: ${account.localId}");
final userInfo = await account.getDetails();
print("User-Info: $userInfo");
// 删除并释放账户
await account.delete();
account.dispose();
示例代码
以下是完整的示例代码,展示了如何使用firebase_auth_rest_2
进行身份验证和账户管理。
文件:example/main.dart
// ignore_for_file: avoid_print
import 'dart:io';
import 'package:firebase_auth_rest_2/firebase_auth_rest_2.dart';
import 'package:http/http.dart' as http;
Future<void> main(List<String> arguments) async {
final client = http.Client();
try {
// 创建Firebase认证实例
final fbAuth = FirebaseAuth(client, arguments[0], 'en-US');
// 登录,设置autoRefresh为true以在后台自动刷新ID令牌
print('正在以匿名用户身份登录...');
final account = await fbAuth.signUpAnonymous(autoRefresh: false);
try {
// 打印本地ID和ID令牌
print('本地ID: ${account.localId}');
print('ID令牌: ${account.idToken}');
// 获取用户信息
print('加载用户信息...');
final userInfo = await account.getDetails();
print('用户信息: $userInfo');
// 删除账户
print('正在删除账户...');
await account.delete();
print('账户已删除!');
} finally {
// 释放账户实例以清理资源
await account.dispose();
}
} on Exception catch (e) {
print(e);
print(
'请将API密钥作为第一个参数传递,并确保启用了匿名认证!',
);
exitCode = 127;
} finally {
// 关闭客户端 - fbAuth及其关联的所有账户将停止工作
client.close();
}
}
更多关于Flutter Firebase认证插件firebase_auth_rest_2的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复