Is Dart compiler able to infer the usage of const constructor? Is Dart compiler able to infer the usage of const constructor? dart dart

Is Dart compiler able to infer the usage of const constructor?


No, Dart compiler does not infer const unless syntactic context requires constness e.g. if you write const [A()] that puts A() into the const context, which means const [A()] is the same as const [const A()], there are few other places where the same applies (e.g. metadata @A()).

In general Dart compiler can't infer const outside of places where language specification requires it to do so because it might potentially alter the semantics of the program. Consider:

class A {  const A();}final Set<A> s = <A>{};void foo(A a) {  s.add(a);}void main() {  foo(A());  foo(A());  print(s.length);}

If compiler would just go around putting const on constructor invocations then this program would print 1, however it should print 2.


Dart cannot infer that you want that object to be const unless there is some context surrounding it that forces it to be const. This is not the case in the example you show. You must use the const keyword at some point if you want dart to make something const.

Example of inferred const:

const SizedBox(  child: Retry(),)

The const on the SizedBox forces Retry to be const. This and similar situations are the only places where const is implied.