Why can't Flutter make "const" default automatically?

499 Views Asked by At

I'm really bothering with the "const" in Flutter 3.0.

Why can't Flutter make "const" default automatically?

Since during editing, it already displays warning about a certain expression having to be "const", it could automatically infer that expression as "const".

Without us having to pollute the code by filling it with "const". The same way he did with "new" in version 2.0.

Is there any impediment for this to be so? I can't imagine any, but if there were, a keyword could be created to say the opposite of "const". It could be the "var", for example.

1

There are 1 best solutions below

4
On

We have option to set const automatically from vs-code setting.

enter image description here

You can check original question on Fix all const warning flutter

Do I like it? No, think about column widget, where children can be const. After writing some children, you find that everything is const . This situation automatic system will provide const before list

  Column(
    children: const [

Now we have added another child which is not const, we need to move at the top and remove the const, then it will auto apply const inner child. Scrolling mouse lose focus of keyboard and cost good amount of time.

As @mmcdon20 included git issue on Compiler should try to make everything const.

You can check the last comment where they mentioned

For history, during the Dart 2.0 language design, we considered automatically making all expressions that could be constant also be constant. Examples included things like Duration(seconds: 1), which might as well be constant.
The reason we ended up not doing so was that the failure modes were scary, and that it wasn't clear how to handle list/map literals.
If you write MyPotentiallyConstantClass(<int>[1]), then that expression can be constant, but it changes the behavior of the list if it is. You get an immutable list, and then there would be syntax to ask that list to be non-constant. We might have to introduce MyPotentiallyConstantClass(new <int>[1]). Even worse, almost every list and map literal seemed like it would default to constant (because it could), and most of those are actually intended to be mutable.