提供者的状态管理 [英] Flutter state management with Provider
问题描述
我有一个简单的提供程序类:
import 'package:flutter/foundation.dart';
class AppState with ChangeNotifier {
bool _isLoggedIn = false;
bool get isLoggedIn => _isLoggedIn;
set isLoggedIn(bool newValue) {
_isLoggedIn = newValue;
notifyListeners();
}
}
在登录类中,如果登录成功,我只需将isLoggedIn
设置为true:
And in the login class I just set isLoggedIn
to true if login is successful:
void _signInWithEmailAndPassword(appState) async {
try {
final FirebaseUser user = await _auth.signInWithEmailAndPassword(
...
);
if (user != null) {
appState.isLoggedIn = true;
appState.userData = user.providerData;
...
}
} catch (e) {
setState(() {
_errorMessage = e.message;
});
}
}
即使成功登录后,按Android上的后退"按钮也可以使用户返回此页面.因此,我想知道是否可以在Widget build
之前访问Provider.of
,并在isLoggedIn
为true
时重定向用户.
Pressing the back button on Android lets users go back to this page even after successfully logging in. So I wanted to know if Provider.of
can be accessed before Widget build
and redirect a user if isLoggedIn
is true
.
现在我有类似的东西:
@override
Widget build(BuildContext context) {
final appState = Provider.of<AppState>(context);
...
这只是登录视图的一种用例,但我确定可以在其他情况下使用此功能.
This is only one use case for the login view, but I'm sure this functionality can be used in other cases.
推荐答案
如果您打算在整个应用程序中使用FirebaseUser或登录"用户,建议您在应用程序的最高级别添加Provider.例子
If you are going to use the FirebaseUser or Logged in user throughout your app, i would suggest that you add the Provider on the highest level of your app. Example
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp();
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
StreamProvider<FirebaseUser>.value(
stream: FirebaseAuth.instance.onAuthStateChanged, // Provider here
),
],
child: MaterialApp(
title: 'My App',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.green,
primarySwatch: Colors.green,
accentColor: Colors.yellow,
),
home: MainPage(),
),
);
}
}
class MainPage extends StatefulWidget {
MainPage({Key key, this.storage}) : super(key: key);
final FirebaseStorage storage;
@override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage>
with SingleTickerProviderStateMixin {
@override
Widget build(BuildContext context) {
final user = Provider.of<FirebaseUser>(context); // gets the firebase user
bool loggedIn = user != null;
return loggedIn ? HomePage() : LoginPage(); // Will check if the user is logged in. And will change anywhere in the app if the user logs in
}
}
参考
这篇关于提供者的状态管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!