Constant constructor in Dart (Flutter)

948

You current code cannot have a const constructor since some of the member variables in the class are not marked as final.

The purpose of const constructor is that if you create multiple instances of the same class with the same arguments on compile time (so all parameters can be determined by the compiler and is not runtime dependent) it will share the same instance in memory. This is only allowed since all member variables is final.

So the advantages is potential performance and memory improvements in specific cases (like some of the classes in dart:convert). But you must call the const constructor like const MyClass(); for getting this const behavior. Else, a const can still be used like a normal constructor to get a normal instance of the class.

Personally, I will say that if you have a class with only final variables which are pointing to other const objects, there are really no reason for not creating a const constructor even if it is never going to be used. But you will often only be able to do this for simple data classes.

But it is also totally fine to not make a const constructor.

Share:
948
König Wey
Author by

König Wey

Updated on December 22, 2022

Comments

  • König Wey
    König Wey over 1 year

    Can someone explain, what the advantages of constant constructors are? If I have a StatefulWidget

    class X extends StatefulWidget {
      const X(this.a, this.b,...);
      A a;
      B b;
    ...
    }
    

    I do not understand why const is used. If I understand correctly, const means it is known at compile time, but what is it for? Usually the attributes a, b, etc. are not known at compile time, but at runtime, so what is the point for the const constructor?