Flutter-何时使用ChangeNotifierProvider发出初始请求?

时间:2019-06-07 23:57:11

标签: flutter python-requests builder

我有一个RootPage类,使用RootModelChangeNotifierProvider提供了一个类。此类的目的是根据用户是否登录来加载适当的窗口小部件。要确定这一点,我在构建器中发出了异步请求(请参见下文)。 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);
      }
    }
  }
}

0 个答案:

没有答案