[英]Flutter Firebase authStateChanges() with Provider & NullSafety On
我見過很多這樣的問題,但其中大多數已經過時,並且沒有使用空安全。
我正在使用 FirebaseAuth 和提供程序來流式傳輸和更新用戶狀態(他是否登錄)
這段代碼有什么問題?
AuthenticationProvider 類
class AuthenticationProvider {
final FirebaseAuth _firebaseAuth;
AuthenticationProvider(this._firebaseAuth);
Stream<User?> get authState => _firebaseAuth.authStateChanges();
}
main.dart
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
Provider<AuthenticationProvider>(
create: (_) => AuthenticationProvider(FirebaseAuth.instance),
),
StreamProvider(
create: (context) =>
context.read<AuthenticationProvider>().authState,
initialData: null,
),
],
child: MaterialApp(
title: 'Flutter Demo',
home: SplashScreen(),
),
);
}
}
SplashScreen() 類
class SplashScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final firebaseUser = context.watch<User>();
if (firebaseUser != null) { // This line warning: The operand can't be null, so the condition is always true. Remove the condition.
return Dashboard();
}
return StartingScreen();
}
}
鑒於您從User?
流開始User?
:
Stream<User?> get authState => _firebaseAuth.authStateChanges();
我認為watch
應該在User?
也。 所以:
final firebaseUser = context.watch<User?>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.