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.