The constructor being called isn’t a const constructor. try removing ‘const’ from the constructor invocation.

When you encounter the error message “the constructor being called isn’t a const constructor. try removing ‘const’ from the constructor invocation,” it means that you are trying to use the ‘const’ keyword to create an object instance with a constructor that is not declared as a const constructor. In other words, you are attempting to invoke a non-const constructor as if it were a const constructor.

In Dart, a const constructor is a constructor that can be used to create a compile-time constant. It is declared using the ‘const’ keyword before the constructor’s name. When using a const constructor, all the instance variables of the class must also be declared as final and initialized with a constant value.

In contrast, a non-const constructor is a regular constructor that can be used to create an object at runtime. It can have mutable instance variables and perform any logic required during the object initialization.

To fix the error, you need to remove the ‘const’ keyword from the constructor invocation and use it to create a non-const object instance. Here’s an example to help illustrate this:

    
class MyClass {
  String name;
  
  // Non-const constructor
  MyClass(this.name);
}

void main() {
  // Error: The constructor being called isn't a const constructor.
  // Try removing 'const' from the constructor invocation.
  const myObject = MyClass('John');

  // Fix: Create a non-const object instance
  final myObject = MyClass('John');

  // Now you can use myObject as a regular non-const object.
}
    
  

In the example above, the class MyClass has a non-const constructor that takes a name parameter. Initially, an attempt is made to create a const object myObject using the const keyword, which results in the mentioned error. However, after removing the const keyword and using the non-const constructor, a valid non-const object instance is created, fixing the error.

Read more interesting post

Leave a comment