我有一个RootPage
类,使用RootModel
为ChangeNotifierProvider
提供了一个类。此类的目的是根据用户是否登录来加载适当的窗口小部件。要确定这一点,我在构建器中发出了异步请求(请参见下文)。 RootModel
,因为ChangeNotifier
将更新状态,并且RootPage
将重建。我应该避免在构建器中发出此请求吗?
RootPage
class RootPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<RootModel>(
builder: (context) {
RootModel model = RootModel(RootState.Init);
model.fetchCurrentUser();
return model;
},
child: Consumer<RootModel>(
builder: (context, model, child) => getWidget(model.state)));
}
Widget getWidget(RootState state) {
switch (state) {
case RootState.NoCommunity:
{
return SearchCommunityPage();
}
case RootState.LoggedIn:
{
return HomePage();
}
case RootState.NotLoggedIn:
{
return WelcomePage();
}
default:
{
return Scaffold(
body: Container(
alignment: Alignment.center,
child: CircularProgressIndicator(),
),
);
}
}
}
}
RootModel
enum RootState { Init, Loading, NotLoggedIn, LoggedIn, NoCommunity }
class RootModel extends BaseModel<RootState> {
final _authService = AuthService();
final _userService = UserService();
RootModel(RootState initialState) : super(initialState);
void fetchCurrentUser() async {
setState(RootState.Loading);
FirebaseUser user = await _authService.current().catchError((e) {
print("login failed: ${e.message}");
});
if (user == null) {
setState(RootState.NotLoggedIn);
} else {
// check if user has a community.
bool hasCommunity = await _userService.hasCommunity(user.uid)
.catchError((e) {
print("community request failed: ${e.message}");
});
if (!hasCommunity) {
setState(RootState.NoCommunity);
} else {
setState(RootState.LoggedIn);
}
}
}
}