Flutter Firebase认证插件lit_firebase_auth的使用
Flutter Firebase认证插件lit_firebase_auth的使用
简介
Lit Firebase Auth
⚠️ 注意:此包处于早期阶段。许多功能尚未实现。最终此包会变得“炫酷”,但目前请自行承担风险。
Lit Firebase Auth 提供了一组方便的工具和小部件,可以轻松地将 Firebase 认证添加到 Flutter 应用程序中。
目录
特性
-
多平台支持
- 支持移动设备(Android/iOS)和 Web。无需修改。
- Windows、macOS 和 Linux 将在未来添加。
-
多个认证提供商
- 支持的包:Google、Apple、Twitter 和 GitHub。
- 请参阅 认证提供商 获取更多信息。
-
服务和状态由 Lit 管理
- 轻松在应用程序的任何地方与 Firebase 交互。
- 监控身份验证状态并响应更改。
-
错误处理和错误消息
- 内置错误处理,将在应用内显示友好的错误消息。
- 可以自定义错误/成功对话框。
-
高度可定制
- 可以使用标准登录小部件,也可以创建自己的。
开始使用
在使用此包之前,请确保已在应用程序中初始化了 Firebase Core。有关最新信息,请参阅官方 FlutterFire 文档。
完整的示例(包含 Firebase 初始化)可以在 示例项目 中查看。
或者查看一个 在线演示。
关于 Lit Firebase 的一些视频:
平台配置
Android 集成
按照正常的 Firebase 初始化 进行操作。
注意:在 Android 上调试时,请使用带有 Google Play 服务的设备或模拟器。否则无法进行身份验证。
iOS 集成
按照正常的 Firebase 初始化 进行操作。
还需要为项目定义全局平台。修改 <project>/ios/Podfile
,确保以下内容未被注释:
platform :ios, '8.0'
可以在 <project>/ios/Podfile
文件顶部找到此内容。
Web 集成
按照正常的 Firebase 初始化 进行操作。
上述内容应该足够,并且应该提供最新的信息。但是,如果需要更多详细信息,请参见以下内容:
您需要根据 Firebase 设置说明修改应用的 <web/index.html>
文件:
在 <web/index.html>
文件中启用 Firebase Auth 的示例如下:
...
<body>
<!-- GOOGLE SignIn Client ID -->
<meta name="google-signin-client_id" content="ADD-YOUR-CLIENT-ID.apps.googleusercontent.com">
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-auth.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
...// ADD CONFIG HERE
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
<!-- CONTINUE TO INITIALIZE FLUTTER WEB -->
...
</body>
使用方法
两个最重要的小部件是:
<code>LitAuthInit</code>
- 用于初始化包并暴露应用程序中使用的服务。<code>LitAuth</code>
- 渲染 UI(表单、按钮和对话框)。
Lit Firebase 初始化
首先,需要使用 <code>LitAuthInit</code>
初始化包。这应该在应用程序的根部。在 <code>MaterialApp</code>/<code>CupertinoApp</code>
之上,并在任何想要访问身份验证功能的小部件之上。
例如:
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
// 需要在 [MaterialApp]/[CupertinoApp] 之上
return LitAuthInit(
// 指定要启用的身份验证提供程序
authProviders: AuthProviders(
emailAndPassword: true, // 默认启用
google: true,
apple: true,
twitter: true,
github: true,
anonymous: true,
),
child: MaterialApp(
title: 'Material App',
home: Home(),
),
);
}
}
标准登录小部件
您可以创建自己的自定义登录小部件,也可以使用内置的标准登录小部件。
要使用默认配置和 UI 主题的标准登录表单:
LitAuth();
这将使用默认配置和 UI 主题。
有关自定义的更多信息,请参阅 装饰和主题 部分。
注意:此小部件需要作为 <code>Scaffold</code>
小部件的子级。
处理身份验证状态变化
要确定当前的身份验证状态,请使用 <code>LitAuthState</code>
:
class Home extends StatelessWidget {
const Home({Key key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
body: LitAuthState(
authenticated: () => Text('Authenticated'), // 登录小部件或登录按钮
unauthenticated: () => Text('Not Authenticated'), // 已登录小部件或注销按钮
),
);
}
}
身份验证成功与失败
可以在 <code>LitAuth</code>
中提供可选回调来处理登录时的成功和失败。
return LitAuth(
onAuthFailure: (failure) {
print('Auth failed.'); // 显示错误消息
},
onAuthSuccess: () {
print('Auth success.'); // 导航到新屏幕
},
);
注意:如果 <code>LitAuth</code>
已经被释放,则这些处理器不会被调用。
例如,如果将此 <code>LitAuth</code>
包裹在 <code>LitAuthState</code>
中,例如:
return LitAuthState(
authenticated: () =>
Text('Authenticated'), // 登录小部件或登录按钮
unauthenticated: () => LitAuth(
onAuthFailure: (failure) {
print('Auth failed.'); // 显示错误消息
},
onAuthSuccess: () {
print('Auth success.'); // 不会被调用
},
),
);
在这种情况下,onAuthSuccess
处理器可能不会被调用。因为 <code>authenticated</code>
状态会被触发并且 <code>LitAuth</code>
小部件被释放。
登出
要登出当前用户,请使用 <code>BuildContext</code>
上的 signOut
扩展方法。例如:
RaisedButton(
onPressed: () {
context.signOut();
},
child: Text('Sign out'),
);
获取当前用户
根据用户的登录状态,您会得到不同的状态:空、初始化或成功。
final litUser = context.getSignedInUser();
litUser.when(
(user) => print(user.uid),
empty: () {},
initializing: () {},
);
value.user
是 Firebase 的 <code>User</code>
对象。
监听用户更改
监视 Firebase 的 <code>User</code>
对象是否有更改。每次 Firebase <code>User</code>
发生更改时都会触发(例如注销或重新登录)。
final litUser = context.watchSignedInUser();
litUser.when(
(user) => Text('Signed in ${user.uid}'),
empty: () => Text('Not signed in'),
initializing: () => Text('Loading'),
);
上述内容仅应在构建方法中使用。如果您需要直接访问当前用户,请优先使用 <code>context.getSignedInUser()</code>
。
判断提交是否正在进行
判断 Lit Firebase 当前是否正在尝试认证。可以用于显示加载指示器。
应仅在构建方法中使用。例如:
Widget build(BuildContext context) {
final isSubmitting = context.isSubmitting();
return Visibility(
visible: isSubmitting,
child: CircularProgressIndicator(),
);
}
认证提供商
Lit Firebase Auth 支持多种第三方认证提供商,如 Google、Apple、GitHub 等。
初始化
在 Firebase 控制台中启用要使用的登录方法。
Google 登录(Android)
Lit Firebase Auth 使用 <code>google_sign_in</code>
包进行 Google 登录。如果遇到困难,请查阅其文档。
请确保已完成 Android 集成 中的步骤。
主要配置在 Firebase 端完成。首先,在 Firebase 项目的身份验证部分启用 Google 登录。接下来,如果尚未完成,请在 Firebase 设置中提供您的应用程序的 SHA 证书,并替换 <code>google-services.json</code>
文件中的更新版本。这是允许 Google 登录所需的。
正确设置的 Firebase 项目和正确的 <code>google-services.json</code>
文件是你所需要的全部。
Google 登录(iOS)
Lit Firebase Auth 使用 <code>google_sign_in</code>
包进行 Google 登录。如果遇到困难,请查阅其文档。
请确保已完成 iOS 集成 中的步骤。
然后将以下 <code>CFBundleURLTypes</code>
属性添加到 <code>[my_project]/ios/Runner/Info.plist</code>
文件中。
<!-- Put me in the [my_project]/ios/Runner/Info.plist file -->
<!-- Google Sign-in Section -->
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<!-- TODO Replace this value: -->
<!-- Copied from GoogleService-Info.plist key REVERSED_CLIENT_ID -->
<string>com.googleusercontent.apps.861823949799-vc35cprkp249096uujjn0vvnmcvjppkn</string>
</array>
</dict>
</array>
<!-- End of the Google Sign-in Section -->
iOS 额外要求
请注意,根据 https://developer.apple.com/sign-in-with-apple/get-started, 从 2020 年 6 月 30 日起,向 Apple App Store 提交的应用程序必须提供“使用 Apple 登录”的选项。
Google 登录(Web)
您需要在 <code>index.html</code>
文件中添加 Google 登录客户端 ID。可以从 Firebase 控制台中的 Google 登录 Web 配置(身份验证部分)中获取此 ID。
示例如下:
...
<body>
<!-- GOOGLE SignIn Client ID -->
<meta name="google-signin-client_id" content="ADD-YOUR-CLIENT-ID.apps.googleusercontent.com">
...
</body>
Apple 登录(Android)
这应该可以正常工作,但尚未经过测试。Firebase 文档中应有配置示例。
Apple 登录(iOS)
- 在 Xcode 中 配置您的应用,添加“使用 Apple 登录”功能。
Twitter 登录(iOS 和 Android)
- 在 Twitter 开发者门户 注册您的应用程序。
- 将 API 密钥和 API 密钥秘密复制粘贴到 Firebase 的 Twitter 登录方法中。
- 在 Twitter 开发者门户中启用第三方身份验证,并从 Firebase 复制粘贴回调 URL。
GitHub 登录(iOS 和 Android)
类似 Twitter 登录的过程。
与其他 Lit Firebase Auth 的集成
支持的第三方提供程序包括:
- Apple
- GitHub
注意:如果使用任何其他第三方登录选项,则需要启用 Apple 登录。
这些需要在 <code>LitAuthInit</code>
小部件中启用。
LitAuthInit(
// 指定要启用的身份验证提供程序
authProviders: AuthProviders(
emailAndPassword: true, // 默认启用
google: true,
apple: true,
twitter: true,
github: true,
anonymous: true,
),
child: MaterialApp(
title: 'Material App',
home: Home(),
),
);
要使用其中一个提供程序发起身份验证,请调用相关的方法。例如:
FlatButton(
onPressed: () {
context.signInWithGithub();
},
child: Text('Github Sign In'),
),
其他身份验证提供程序(例如 Facebook)需要单独实现。在成功进行第三方登录后,可以通过在 <code>BuildContext</code>
上调用 <code>signInWithCredential</code>
方法来登录 Firebase。
例如:
Widget build(BuildContext context) {
AuthCredential credential = // 获取身份提供程序的凭据(Facebook 等)
context.signInWithCredential(credential);
}
装饰和主题
UI 可以根据您的需求进行高度定制。但对于简单的使用情况,它非常简单。
很容易为登录元素提供自定义装饰/配置。您可以要么自定义标准登录小部件的元素,要么完全从头创建自定义登录小部件。由您决定。
标准登录小部件的自定义
例如,要覆盖标准的电子邮件 <code>TextFormField</code>
,只需为 <code>emailTextField</code>
参数提供一个 <code>TextFieldConfig</code>
。在此示例中,我们提供了新的 [样式]
和 [输入装饰]
:
return LitAuth(
config: AuthConfig(
emailTextFormField: InputDecoration(labelText: 'My beautiful label'),
emailTextField: TextFieldConfig(
style: TextStyle(fontSize: 18),
inputDecoration: InputDecoration(
labelText: 'My beautiful label',
),
),
)
);
要自定义按钮:
return LitAuth(
config: AuthConfig(
signInButton: ButtonConfig.raised(
themedata: ButtonThemeData(buttonColor: Colors.red),
child: Text('Sign in with Email'),
),
googleButton: GoogleButtonConfig.light(),
appleButton: AppleButtonConfig.dark(),
),
),
有许多不同的按钮自定义方式可以执行。
通知
通知使用 <code>flushbar</code>
包渲染。
您可以自定义错误和成功通知:
LitAuth(
errorNotification: NotificationConfig(backgroundColor: Colors.pink),
successNotification: NotificationConfig(backgroundColor: Colors.pink),
);
有许多属性可以更改以创建所需的通知。请参阅 <code>NotificationConfig</code>
类以获取更多信息。
其他自定义
对于进一步的定制,可以直接使用 Lit Firebase 组件来构建完全自定义的登录小部件。
而不是使用标准 <code>AuthConfig</code>
,将其设置为自定义并提供您自定义的登录小部件:
return LitAuth.custom(
child: YourCustomSignInWidget(),
);
您可以构建任何表单,例如:
class YourCustomSignInWidget extends StatelessWidget {
const CustomSignInWidget({Key key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return Column(
children: [
Text('Welcome', style: Theme.of(context).textTheme.headline4),
// 您需要将自定义登录小部件包装在 [SignInForm] 中。
// 这用于验证电子邮件和密码
SignInForm(
formChild: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'A custom form',
style: Theme.of(context).textTheme.headline5,
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: EmailTextFormField(
style: TextStyle(fontSize: 18),
decoration: InputDecoration(labelText: 'My Email Label'),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: PasswordTextFormField(
style: TextStyle(fontSize: 18),
decoration: InputDecoration(labelText: 'My Password Label'),
),
),
RaisedButton(
onPressed: () {
context.signInWithEmailAndPassword();
},
child: Text('Sign In'),
),
FlatButton(
onPressed: () {
context.signInAnonymously();
},
child: Text('Anony Sign In'),
),
],
),
),
],
);
}
}
注意:SignInForm
需要提供在 <code>EmailTextFormField</code>
和 <code>PasswordTextFormField</code>
之上。
可以通过调用来手动清除密码和电子邮件的状态:
context.resetSignInForm()
这将重置表单到初始状态。
当您在不同位置有多个 <code>EmailTextFormField</code>
和 <code>PasswordTextFormField</code>
小部件时,这是一个好主意,例如当您有独立的登录表单和注册表单时。
图标
可以使用包中提供的 OAuth 图标。例如:
class Icons extends StatelessWidget {
const Icons({Key key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return Column(
children: [
LitAuthIcon.google(),
LitAuthIcon.appleBlack(),
LitAuthIcon.appleWhite(),
LitAuthIcon.github(),
LitAuthIcon.twitter(),
],
);
}
}
更多关于Flutter Firebase认证插件lit_firebase_auth的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter Firebase认证插件lit_firebase_auth的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
lit_firebase_auth
是一个用于 Flutter 的 Firebase 认证插件,它简化了 Firebase 认证流程,并提供了一些便捷的功能。以下是如何在 Flutter 项目中使用 lit_firebase_auth
插件的基本步骤。
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 lit_firebase_auth
和 firebase_core
依赖:
dependencies:
flutter:
sdk: flutter
firebase_core: latest_version
lit_firebase_auth: latest_version
然后运行 flutter pub get
来安装依赖。
2. 初始化 Firebase
在 main.dart
文件中初始化 Firebase:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomeScreen(),
);
}
}
3. 使用 lit_firebase_auth
进行认证
lit_firebase_auth
提供了一些便捷的 Widget 和方法来处理 Firebase 认证。以下是一个简单的示例,展示如何使用 lit_firebase_auth
进行电子邮件/密码认证。
登录页面
import 'package:flutter/material.dart';
import 'package:lit_firebase_auth/lit_firebase_auth.dart';
class SignInScreen extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Sign In'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: LitSignInForm(
onSignInSuccess: () {
// 登录成功后导航到主页
Navigator.of(context).pushReplacementNamed('/home');
},
onSignInFailed: (error) {
// 处理登录失败
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(error.message)),
);
},
),
),
);
}
}
注册页面
import 'package:flutter/material.dart';
import 'package:lit_firebase_auth/lit_firebase_auth.dart';
class SignUpScreen extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Sign Up'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: LitSignUpForm(
onSignUpSuccess: () {
// 注册成功后导航到主页
Navigator.of(context).pushReplacementNamed('/home');
},
onSignUpFailed: (error) {
// 处理注册失败
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(error.message)),
);
},
),
),
);
}
}
主页
import 'package:flutter/material.dart';
import 'package:lit_firebase_auth/lit_firebase_auth.dart';
class HomeScreen extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
actions: [
IconButton(
icon: Icon(Icons.logout),
onPressed: () {
// 登出
LitAuthState.of(context).signOut();
},
),
],
),
body: Center(
child: Text('Welcome!'),
),
);
}
}
4. 导航设置
在 MaterialApp
中设置路由导航:
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
routes: {
'/': (context) => SignInScreen(),
'/signup': (context) => SignUpScreen(),
'/home': (context) => HomeScreen(),
},
);
}
}