2

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.

5
  • 1
    Edit question and share your code please Commented May 15, 2020 at 14:45
  • 1
    It happened because I had called setState((){}) within the callback passed to WidgetsBinding.instance.addPostFrameCallback. So the widget re-built itself after every (successful) build. Commented May 25, 2020 at 15:03
  • @NephewofStackoverflow I have the same problem like yours, had you found any solution? Commented Feb 8, 2021 at 8:11
  • Yes, It was because setState was being called within the callback. Commented Feb 8, 2021 at 16:59
  • Don't use WidgetsBinding.instance.addPostFrameCallback and setState within the build method. Commented Apr 12, 2021 at 9:14

2 Answers 2

5

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(() {}));
Sign up to request clarification or add additional context in comments.

1 Comment

Can this be used at any app stage or only initState?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.