在构建过程中构建飞镖 /颤动中的错误



因此,在我的构建函数中,我加载了用户数据,一旦加载了用户数据,我想更改应用程序的主题(call setState())。问题是我在构建过程中无法调用SetState,例如下面的错误状态。如何在应用程序启动上加载用户选择的主题?另外,是否不建议将数据加载到构建功能中?它似乎运行良好,但感觉有些粗糙。谢谢!

Widget build(BuildContext context) {
    //get user object from Firebase
    //once user is loaded, take their chosen color theme and call updateTheme()
}

错误:

This ThemeSwitcherWidget widget cannot be marked as needing to build because the framework is
I/flutter (23889): already in the process of building widgets. A widget can be marked as needing to be built during the
I/flutter (23889): build phase only if one of its ancestors is currently building. This exception is allowed because
I/flutter (23889): the framework builds parent widgets before children, which means a dirty descendant will always be

用于加载数据或进行阻止调用,您应该使用futurebuilder或streambuilder(我不太了解Firebase API非常相似。)需要将来或流作为参数,并基于它构建。我假设您知道DART的未来API

这是一些示例代码,可以给您一些想法。

StreamBuilder<FirebaseUser>(
  stream: FirebaseAuth.instance.onAuthStateChanged,
  builder: (BuildContext context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return new SplashScreen();
    } else {
      if (snapshot.hasData) {
        return new MainScreen(firestore: firestore, uuid: snapshot.data.uid);
      }
      return new LoginScreen();
    }
  }
)

最新更新