Reputation: 3424
I have seen many questions like this, but most of them are outdated and not using null safety.
I am using FirebaseAuth and provider to stream & update the users state (Is he logged in or not)
what's wrong with this code?
AuthenticationProvider Class
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
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();
}
}
Upvotes: 2
Views: 1714
Reputation: 600141
Given that you start with a stream of User?
:
Stream<User?> get authState => _firebaseAuth.authStateChanges();
I think the watch
should be on User?
too. So:
final firebaseUser = context.watch<User?>();
Upvotes: 4