'WidgetsBinding.instance.addPostFrameCallback gets called multiple times while using setState

For some reason whenever I use setState((){}); in the function I pass in WidgetsBinding.instance.addPostFrameCallback(), that function gets called multiple times.

Is there any way to overcome it?

Note: Both the code within and outside the setState get called.



Solution 1:[1]

You can call setState after rendering is done by adding a post frame callback with addPostFrameCallback method. This will be called only once and after build process is done.

WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {}));

Solution 2:[2]

I know this is old, but on my hand, the solution by @M???Q???k?V?.0 wasn't working, unfortunately (still called several time).

Only way for me was to create an async function and call it before building the rest, it will be executed after build:

//Works perfect for me
  Future<void> _asyncFunctionAfterBuild() async {
    setState(() {
      print("check if i'm printed several times!");
    });
 }

[...]

  @override
  Widget build(BuildContext context) {
    _asyncFunctionAfterBuild();
    return Text("Blabla");
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MαπμQμαπkγVπ.0
Solution 2 Baptiste V