DEV Community

Cover image for Flutter Performance Tips (#1): const constructors
Pedro Massango
Pedro Massango

Posted on

Flutter Performance Tips (#1): const constructors

When we use setState() Flutter calls the build method and rebuilds every widget tree inside it. The best way to avoid this is by using const costructors.

Use const constructors whenever possible when building your own widgets or using Flutter widgets. This helps Flutter to rebuild only widgets that should be updated.

So if you have a StatefulWidget and you are using setState((){}) to update that widget and you have widgets like:

class _MyWidgetState extends State<MyWidget> {

  String title = "Title";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Column(
        children: <Widget>[
          const Text("Text 1"),
          const Padding(
            padding: const EdgeInsets.all(8.0),
            child: const Text("Another Text widget"),
          ),
          const Text("Text 3"),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () {
          setState(() => title = 'New Title');
        },
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

If you run this code and press the floating action button, all the widgets defined as const won't get rebuilded.

Top comments (22)

Collapse
 
remejuan profile image
Reme Le Hane

So what is the actual performance benefit here? You say we should do this for the benefit of performance with no cost analysis.

I have seen similar arguments for using bind over const in react classes but when you dig down the performance benefit only become applicable after 1 million iterations, making the performance "benefit" non existent for over 99.9% of Web applications and at the point in time you reaping the benefits you need to reevalutw your life choices for somehow managing to have written what could conceivably be the worst code ever written.

Not saying your wrong, but your not giving any actual reason other than "because I say so".

Collapse
 
pedromassango profile image
Pedro Massango

The benefits is that the widgets declared as const won't get rebuilded when you use setState().

Collapse
 
remejuan profile image
Reme Le Hane

You mentioned that, but what is the actual benefit, is the app gonna be faster, smoother. What is the benefit for the dev or the end user in a text element not rerendering?

The exact same argument was made for the example. I mentioned, but again if it not rendering saves you 0.0000001ms on render the benefit is practically non existent and it's over optomization at the cost of readibilty with no real world benefit.

Thread Thread
 
tatsuukraine profile image
Denis Beketsky

Benefit of using const is that such items will be compiled once during AOT

Thread Thread
 
remejuan profile image
Reme Le Hane

Still not answering the ACTUAL question. So what if it renders twice, is it going to slow things down, blow up the users phone, what.

We adding a bunch of words to decrease code legibility for what actual reason.

Once vs twice vs 100 times what does it actually matter. Sure in a blog post it sounds like a good idea to not waste renders, but in reality a render works from the top down if the engine is optimal it will know the text element has not changed and carry on with its job to do a dif will take a fraction of a millisecond.

You get new devs coming to this, taking the word as gospal as they do not have the experience to think 'why' and end up with bugs and side effects as they have no idea why they doing it or if they even really should and they can't know if they should unless they know the actual why the actually benefit, the actual reason why this is better than not doing it, what is this going to do to improve the user experience, what is this going to do to my apps performance and more importantly when they should not do this which can hopefully be inferred from the actual reason why.

People seem to forget there is such a thing as over optomizing, something very easily achieved when you accept 'because I said so' as a valid and ultimately, unquestionable reason.

I find it shocking that I am the only developer not finding some random blog post online as gospel truth. Maybe we should do it, maybe we should not, when do we and when don't we and why why why are all questions not being answered.

Thread Thread
 
tatsuukraine profile image
Denis Beketsky

I think it's just a question of overall optimization. Using const allows you to minimize memory allocation, also it allows you to define such items only once during AOT compilation. It's definetly not improve your app performance significantly, but using const will make it a little bit faster. If you have for instance 100 items probably this const optimization won't make huge performance boost. You can search across internet how dart treats with const variables. For example you can take a look in official docs about StatelessWidget under Performance considerations section

Thread Thread
 
pedromassango profile image
Pedro Massango • Edited

Lets say that it is a small performance improvement, but it can add up in larger apps or apps where the view is rebuilt often for example because of animations.
const reduces the required work for the Garbage Collector.

(Updates)
Read more:
api.flutter.dev/flutter/widgets/St...

Collapse
 
mahmoudsalah37 profile image
Mahmoud salah eldien saber

bad :-

const Padding(
padding: const EdgeInsets.all(8.0),
child: const Text("Another Text widget"),
),

Good :-

const Padding(
padding: EdgeInsets.all(8.0),
child: Text("Another Text widget"),
),

Collapse
 
dqk profile image
K

Hi. Why the first one is bad and the second one is good? Can you give me an explanation? Tks.

Collapse
 
pedromassango profile image
Pedro Massango

In short, because when you mark the top-most widget in the tree with a const keyword, all its inner widgets will also use a const constructor, so there is no need to add those extra const keywords. If a inner widget does not have a const constructor, then your code won't compile.

Collapse
 
frankzang profile image
Francisco Santos

It seems nice but did you do any measurements on how this impacts the overall performance?

Collapse
 
pedromassango profile image
Pedro Massango

I didn't but by knowing that: a const widget won't be re-created everytime its parent widget rebuilds, we can assume a performance improvement, why? because it is less widget for the framework to care about during rebuilds.

Collapse
 
ejthayer profile image
ejthayer • Edited

I'm sorry but this is just wrong. I'm a bit of a speed nut, as soon as Flutter came out I started testing its speed. I wanted to know if it was game capable, and it is. I have also done tests with 2 flutter pages. Both with tons of widgets, one page no const, the other page mostly const, refreshing the page 10000 times and timing to the nearest millisecond and there was no significant difference at all. If it was a valid way to increase speed I would love it, but it is just not. If people want to gain speed you should focus on not having redundant embedded widgets or improperly using state management. In fact most developers improperly use state management, start there.

Collapse
 
morn profile image
Magnús Örn Gylfason

Do you even need to do this now? Doesn't the compiler assume "const" wherever it can?

Collapse
 
pedromassango profile image
Pedro Massango

Yes you need to do this

Collapse
 
premmmm profile image
S.Prem Raj

Hey, I just came across this, I have been developing apps for over a year now, I suddenly saw a "const" keyword in one Instagram post and was curious on why it was used, your post and comment section made it clear. Thanks a ton 💯. Learnt something new today.

Collapse
 
vinceramces profile image
Vince Ramces Oliveros

const and new are optional in dart.

This was the very first problem dealing with how to differentiate the new and const keyword when learning flutter.

Collapse
 
mahiznan profile image
மகிழ்நன்

const is optional in a const context. Refer the stack over flow post @stackoverflow.com/questions/525811...

Collapse
 
newtonmunene_yg profile image
Newton Munene

This is Interesting. I had no idea.

Collapse
 
premmmm profile image
S.Prem Raj

Same, saw this in an instagram post, this is insane.

Collapse
 
danielgomezrico profile image
Daniel Gomez

Can you give show how to actually confirm that you got a perfomrance gain with using const?

Collapse
 
danielgomezrico profile image
Daniel Gomez

Is there any way to measure how this impact build time? maybe using firebase performance monitor?