在 2019 年,我设法检查了用户是否登录了该应用程序。不幸的是,从那以后发生了很多变化。我尝试搜索有关 FlutterFire 的教程和指南。但是,我找不到任何东西。我对stream
,future
和感到很困惑provider
。我也不知道他们之间的区别。
我的旧代码(不再起作用):
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);
}
}
}
如何检查用户是否登录?预先感谢您的帮助。