skip to Main Content

When creating a flutter app in the dart language, a hint message is given to attach a const keyword in front of SizedBox.

It is understood that attaching the const keyword increases execution speed by not performing unnecessary calculations at runtime and saves memory by not creating the same object twice.

Then, I wondered if SizedBox was not used from the start of the app to the end of the app, was it using unnecessary memory at compile time?

Also, what I’m still confused about is that memory is allocated at compile time when the const keyword is added, does that mean memory is allocated when the app is installed?

Does that mean it is stored in the internal memory?

On the other hand, what is calculated at runtime and put in memory is put in RAM?

2

Answers


  1. in my opinion, you use const keyword before some widget when parent of this widget rebuild this widget not rebuild again. You can try to wrap two stateful widget (A and B, A is parent widget of B) and call setState function, widget B will not run into build again! So when screen render again, if widgets have const keyword before, this don’t rebuild again, it’s better for performance!

    Login or Signup to reply.
  2. To expand on the answer given by ThanhNguyen, you should use const wherever possible because const tells the dart compiler that once a function or widget is run it will always remain the same and won’t change. The build method is called very often in flutter. So, when build method is called by the flutter framework, a widget which is declared by const keyword, allows flutter to shortcuit the build method and avoid doing most of the work again and again. Because the build method is called whenever the state of widget is changed, build method is called many times in the same widget.

    For ex:
    When creating a container, with a radius

    Container(
       decoration: const BoxDecoration(
           radius: BorderRadius.circular(10)
       ),
    )
    

    When flutter framework builds this container, the const keyword when defining decoration of container helps fluter know that the decoration of container hasn’t changed, and it doesn’t have to clip the container again as the decoration is constant. This causes build method to execute fast.

    To answer your second question:
    No, it is not stored in your internal memory. Compile time means when the app is opened, dart compiler compiles the project into native code, and the variable defined by const keyword is saved during compiling and there is no need of compiling the value of that variable again when running the app.

    Flutter Documentation tells about more performance optimizations that can be done. See here: Performance Best Practices

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search