构建期间Dart / Flutter中的构建错误

时间:2019-02-21 06:24:49

标签: firebase dart flutter google-cloud-firestore

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

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

1 个答案:

答案 0 :(得分:0)

对于加载数据或进行阻塞调用,您应该使用FutureBuilderStreamBuilder(我对firebase API的了解不多,因此无法确定要使用哪个API,但是两者都是非常相似。)它以Future或stream作为参数,并以此为基础进行构建。我假设您知道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();
    }
  }
)