In 2019, I managed to check whether a user is logged in to the app or not. Unfortunately, a lot has changed since then. I've tried searching for tutorials and guides on FlutterFire. But, I couldn't find any. I'm so confused about stream
, future
, and provider
. Nor do I know the difference between them.
My old code (doesn't work anymore):
Future main() async {
runApp(
ChangeNotifierProvider<AuthService>(
child: MyApp(),
create: (BuildContext context) {
return AuthService();
},
),
);
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp, DeviceOrientation.portraitUp]);
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'TestApp',
theme: ThemeData(primarySwatch: Colors.blue),
home: FutureBuilder<FirebaseUser>(
future: Provider.of<AuthService>(context).getUser(),
builder: (context, AsyncSnapshot<FirebaseUser> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// log error to console
if (snapshot.error != null) {
print("error");
return Text(snapshot.error.toString());
}
// redirect to the proper page
return snapshot.hasData ? HomePage() : LoginPage();
} else {
// show loading indicator
return LoadingCircle();
}
},
),
);
}
}
class AuthService with ChangeNotifier {
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<FirebaseUser> getUser() {
return _auth.currentUser();
}
Future logout() async {
var result = FirebaseAuth.instance.signOut();
notifyListeners();
return result;
}
Future<FirebaseUser> loginUser({String email, String password}) async {
try {
var result = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
notifyListeners();
return result.user;
} catch (e) {
throw new AuthException(e.code, e.message);
}
}
}
How do I check whether a user is logged in or not? Thank you in advance for your help.