How does setState schedule build() in Flutter? Or how does setState works under the hood?

Viewed 25

I tried running this code:

void main() {
 runApp(const MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
 const MyApp({Key? key}) : super(key: key);

 @override
 State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
 @override
 Widget build(BuildContext context) {

   // calling setState intentionally !
   setState(() {
     print('looping');
   });

   return Scaffold(
     body: Container()
   );
 }
}

I am calling setState inside build function(Just out of curiosity). I was expecting some error like 'setState() or markNeedsBuild() called during build.' or at-least an infinite loop of rebuilds. But nothing happened and app ran perfectly. If I call setState asynchronously (Using Future.delayed) rebuilds occur indefinitely. Why is it so?.

Another doubt that I have is, if setState is called in initState() or didChangeDependencies(), build function isn't called, why?

I know setState will be called eventually and it is meaningless to call before Widget build. I wanted to know how is scheduling of builds occurring. Documentation: setState causes the framework to schedule a build for this State object.

1 Answers

setState "marks" the widget as "needs rebuilding". So if you call setState while it is rebuilding it nothing will happen because it is already rebuilding. If the build method finishes the "needs rebuilding" is fulfilled and thus it does not run again.

If you however call setState while it is not building it will trigger a new rebuild. So if you use an asynchronous setState in a Future it will mark it as "needs rebuild" AFTER the build method ends.

Related