Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create both const and non-const objects of one class?

So, as far as I know to be able to create a const object of a class in dart you are required to declare const constructor and mark all the fields as final. Then to create a const object of the class you put a const key word before instantiating and to create non-const you don’t put anything. But then if every class in dart is required to have final fields and const constructor to have ability to be const, how can we create both const and non-const objects of default types and be able to change it’s content (for example: we can create both const and non-const List and we can change content of non-const List using [] operator)?

I assume all those default types have only final fields and when we change content it actually creates another instance with changed content and refers to it. Am I right?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In Dart, you’re correct that to create a const object of a user-defined class, you need to have a const constructor and declare all fields as final. However, this rule doesn’t apply to built-in types like List, Map, and other collections or default types. These built-in types do not have const constructors in the same way user-defined classes do.

Default types like List are typically mutable, which means you can change their content. When you modify a List, it doesn’t create a new instance every time you change it; instead, it modifies the existing instance. This is because these built-in types are designed to be flexible and mutable.

For example, when you modify a List, you’re working with the same instance, and the changes are reflected immediately:

var myList = [1, 2, 3];  // Creating a List
myList[0] = 4;          // Modifying the List
print(myList);          // Output: [4, 2, 3]

This behavior is different from const objects, where the immutability is enforced at the language level, and creating a new instance is necessary to make changes.

You can create both const and non-const instances of built-in types, like List, and change the content of non-const instances without any issues. Built-in types are generally designed for flexibility and performance, while user-defined classes give you more control over immutability and customization.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading