Home > Software engineering >  Why doesn't an infinite loop occur when calling setState inside the build function?
Why doesn't an infinite loop occur when calling setState inside the build function?

Time:01-07

I don't understand, why calling setState inside build doesn't occur infinite loop.

For example:

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    callSetState();
    return Container();
  }

  void callSetState() {
    setState(() {});
  }
}

Its really weird for me. Could anyone explain me please?

CodePudding user response:

  • Because the widget is not in the mounted state yet. Can't handle setState
  • If you give a little delay, it is indeed an endless loop. look this.
  void callSetState() {
    print('over!');
    Future.delayed(Duration(seconds: 1), () {
      setState(() {});
    });
  }
  • Related