Jardo
Jardo

Reputation: 2093

Flutter: is calling setState() multiple times inefficient?

Lets say I have a method onButtonPressed() which calls method a() and then method b(). Both methods a() and b() contain a call to setState():

void onButtonPressed() {
    ...
    a();
    ...
    b();
}

void a() {
    ...
    setState() {
        ...
    }
}

void b() {
    ...
    setState() {
        ...
    }
}

Does calling setState() twice cause the affected components to be rendered twice, or is Flutter optimized so that the components only get rendered once?

Upvotes: 4

Views: 3949

Answers (3)

Sebastian
Sebastian

Reputation: 3894

You could do this

void onButtonPressed() {
  ...
  a();
  ...
  b();
  setState((){});
}

So you are calling setState in only one place

Upvotes: -4

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657078

There is a tiny overhead that every call to a function call cost, but this is negligible.

This does not cause an additional overhead from or for the framework.

Upvotes: 3

Rémi Rousselet
Rémi Rousselet

Reputation: 276891

If all of your setState calls happen within the same frame, then there's no issue.

The widget will rebuild once and only once.

Once a widget is marked as needing build, all subsequent calls to setState will do nothing but call the callback until a frame is scheduled and the build is done.

Upvotes: 8

Related Questions