简体   繁体   中英

Build Error in Dart / Flutter during build

So in my build function, I load my user data, and once it is loaded I would like to change the theme of the app (which calls setState()). The issue is that I can't call setState during the build process, like the error below states. How would I go about loading a user selected theme on app startup? Also, is it not recommended to be loading data inside the build function? It seems to work well but feels kinda gross. Thanks!

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

Error:

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

For loading data or doing a blocking call, you should use FutureBuilder or StreamBuilder (I am not much aware of firebase APIs so can't tell which one to use, but both of them are very similar.) It takes a future or stream as an argument and builds based on it. I am assuming you know about future API of dart

Here is some example code that will give you some idea.

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();
    }
  }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM