0

Lets say I have the following:

var example = SizedBox();

dart then recommends that I add const before SizedBox:

var example = const SizedBox();

I understand what the const keyword does, but what I don't understand is why I have to write it in the example above, since the constructor of SizedBox is const. Wouldn't all instances of SizedBox be constant without writing it each time?

Hannes HultergÄrd
  • 1,157
  • 1
  • 11
  • 33

1 Answers1

2

Wouldn't all instances of SizedBox be constant each time without writing it

It seems like that but it is not the case, it does a create a new instance if you don't use const explicitly. The reason is that the linter recommends you to add it is to improve memory allocation i.e. allocate lesser memory because the nature of SizedBox is such that it doesn't have to change because it is indeed a sized box which once initialized doesn't have to change

You can read some more interesting facts on this post

So TLDR:

Why? To save memory and improve hot reload performance and prevent re-rendering How? Read the above post

gtxtreme
  • 1,830
  • 1
  • 13
  • 25