List and Set Literals in Dart#
Using const for Immutable Collections#
How It Works#
In Dart, collections like Lists and
Sets can be made immutable by using the
const keyword. An immutable collection is a collection
that cannot be modified after it is created. This is useful when you
want to ensure that the values within a collection remain constant
throughout the lifecycle of the program, preventing accidental
changes.
-
A constant list or set is
created using the
constkeyword before the collection literal. -
Any attempt to modify a
constcollection (e.g., adding or removing elements) will result in a runtime error.
How to Use#
You use the const keyword before the literal to declare
a collection as immutable. The const keyword can be
applied to list literals and
set literals in Dart. This can be useful in
situations where you need guaranteed unchanging values, such as
configuration settings or default states.
Syntax:#
const List<int> myList = [1, 2, 3];
const Set<String> mySet = {'apple', 'banana', 'cherry'};
- List: A constant list is defined by using const before the list literal.
- Set: Similarly, a constant set is declared using const before the set literal.
## Example
## Example 1: Creating a Constant List
```dart
void main() {
const List<int> numbers = [1, 2, 3, 4];
// Trying to modify the list will cause an error:
// numbers.add(5); // This will throw an error: Unsupported operation
print(numbers); // Output: [1, 2, 3, 4]
}
In this example, the numbers list is immutable, and attempting to modify it will result in an error.
Example 2: Creating a Constant Set#
void main() {
const Set<String> fruits = {'apple', 'banana', 'orange'};
// Trying to modify the set will cause an error:
// fruits.add('grape'); // This will throw an error: Unsupported operation
print(fruits); // Output: {apple, banana, orange}
}
In this example, the fruits set is immutable, and adding or removing items from it is not allowed.
Benefits of Using const Collections#
- Safety: Prevents accidental modification of data.
- Performance: Constant collections may be optimized by the compiler, improving performance.
- Shared Instances: If the same const collection is declared multiple times, Dart will reuse the instance in memory, reducing memory usage.
Conclusion#
Using const for lists and sets ensures that your collections are immutable, making your code more robust by preventing unintended modifications. This is particularly helpful when dealing with data that should remain unchanged once defined.