The `const` constructor
- Dominant language
- No language data
- Stars
- 45
- Forks
- 11
- PR merge metrics
- No merged PRs in 30d
Description
I recently blocked on a line similar to:
```dart
final myList = const [1,2,3];
```
I wan't sure about the meaning of `const` when initialising a `final` variable.
In this situation `const` is used to instanciate (create) a new immutable object.
This means that the list object `[1, 2, 3]` can't be changed, and the following code won't work:
```dart
final myList = const [1, 2, 3];
myList.add(4); // error
```
If we ignore `const` then we are able to use the function `add` on the list, and this following code will work:
```dart
final myList = [1, 2, 3]
myList.add(4) // myList contains now the value [1, 2, 3, 4]
```
ref:
- https://dart.dev/guides/language/language-tour#constructors
- https://dart.dev/guides/language/language-tour#using-constructors
- https://stackoverflow.com/questions/21744677/how-does-the-const-constructor-actually-work/21746692#21746692
- https://stackoverflow.com/questions/52581148/when-is-const-optional-in-dart-2
Contributor guide
No contributing guide indexed for this repository
Research direction
Start by reading the linked Dart language-tour sections on constructors and using constructors, then compare their explanation with the examples in this issue. Clarify the distinction between final variables and const objects, including whether a const list can be modified, and show the contrasting behavior in the learning material.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- dart
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100