Flutter Firebase认证插件flutter_firebase_auth_facade的使用
Flutter Firebase认证插件flutter_firebase_auth_facade的使用
使用此插件作为库
1. 依赖它
在你的包的pubspec.yaml
文件中添加以下依赖:
dependencies:
flutter_firebase_auth_facade: latest_version
2. 安装它
你可以通过命令行安装包:
$ flutter pub get
3. 导入它
现在可以在你的Dart代码中导入该包:
import 'package:flutter_firebase_auth_facade/flutter_firebase_auth_facade.dart';
4. 使用它
可用的方法
方法 | 状态 |
---|---|
CurrentUser |
V |
registerWithEmailAndPassword |
V |
signInWithEmailAndPassword |
V |
SignInWithGoogle |
V |
SignInWithApple |
V |
SignInAnonym |
V |
SigninWithGitHub |
V |
SignInWithFacebook |
X |
SignInWithInstagram |
X |
SignOut |
V |
userState |
V |
resetPassword |
V |
准备Android和iOS
Android
在你的AndroidManifest.xml
文件中添加以下内容:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="https"
android:host="[your firebase project name].firebaseapp.com" />
</intent-filter>
iOS
在你的info.plist
文件中添加以下内容:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>[your firebase project name].firebaseapp.com</string>
<key>CFBundleURLSchemes</key>
<array>
<string>https</string>
</array>
</dict>
</array>
首先实例化FirebaseAuthFacade
并注入GoogleSignIn
和FirebaseAuth
。然后你需要调用实例上的call()
方法,例如authFacade()
。回调URL是必需的,你可以在Firebase面板的GitHub或Apple登录方法中找到它。
你可以像这样使用injectable
并将其实例注入到你的Bloc
中:
import 'package:flutter_firebase_auth_facade/flutter_firebase_auth_facade.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:injectable/injectable.dart';
@module
abstract class PackagesInjectableModule {
@lazySingleton
IAuthFacade get authFacade {
final _firebaseAuth = FirebaseAuth.instance;
final _googleSignIn = GoogleSignIn();
final authFacade = FirebaseAuthFacade(_firebaseAuth, _googleSignIn);
authFacade(
callbackUrl:
environment == Environment.dev ? callbackUrlDev : callbackUrl,
githubClientId:
environment == Environment.dev ? githubClientIdDev : githubClientId,
githubSecret:
environment == Environment.dev ? githubSecretDev : githubSecret,
);
return authFacade;
}
}
实际生活中的例子
你可以在以下开源项目中找到实际应用的例子: flutterence
简单的例子
登录方法返回一个Future<Either<AuthFailure, unit>>
,因此你需要使用Dartz
并折叠结果,例如:
final failureOrSuccess = _authFacade.signInWithGitHub();
failureOrSuccess.fold(
(failure) => print(failure), // 在这里处理失败
(success) => print("User logged in") // 在这里处理用户
);
处理错误
AuthFailure
类使用Freezed进行代码生成,因此你可以使用联合/密封类功能:
failure.map(
// ...
);
failure.maybeMap(
// ...
);
failure.when(
// ...
);
// etc...
依赖项
示例代码
main.dart
import 'package:example/bloc/auth_bloc.dart';
import 'package:example/injections.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:injectable/injectable.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
configureInjection(Environment.prod);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return SplashPage();
}
}
class SplashPage extends StatelessWidget {
const SplashPage({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return FutureBuilder(
future: Firebase.initializeApp(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return BlocProvider(
create: (_) => getIt<AuthBloc>()
..add(const AuthEvent.authCheckRequested()),
child: BlocBuilder<AuthBloc, AuthState>(builder: (context, state) {
if (state is Authenticated) {
return const SplashView(text: 'authenticated');
} else if (state is Unauthenticated) {
return SplashView(
text: 'unauthenticated', homeContext: context);
} else {
return const SplashView();
}
}));
} else if (snapshot.hasError) {
return const SplashView(text: 'Error With Firebase');
} else {
return const SplashView();
}
});
}
}
class SplashView extends StatelessWidget {
const SplashView({Key? key, this.text, this.homeContext}) : super(key: key);
final String? text;
final BuildContext? homeContext;
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: text == null
? const CircularProgressIndicator()
: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
Text(text!),
BlocProvider.value(
value: BlocProvider.of<AuthBloc>(context),
child: BlocBuilder<AuthBloc, AuthState>(builder: (context, state) {
return TextButton(
onPressed: () => state is Unauthenticated
? context.read<AuthBloc>().add(const AuthEvent.loginWithGithub())
: print('ok'),
child: const Text('action'));
}),
)
]),
),
);
}
}
更多关于Flutter Firebase认证插件flutter_firebase_auth_facade的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复