Home>
// sample1 (Dartpad)
var ol = ['Tokyo','Delhi','Shanghai','Mumbai','Beijing'];
void main () {
  List<String>cities = ol;
  cities.sort ();
  print ("ol ==>$ol");
  print ("cities ==>$cities");
}
/ *
ol ==>[Beijing, Delhi, Mumbai, Shanghai, Tokyo]
cities ==>[Beijing, Delhi, Mumbai, Shanghai, Tokyo]
* /
// sample2 (Dartpad)
const ol = ['Tokyo','Delhi','Shanghai','Mumbai','Beijing'];
void main () {
  List<String>cities = ol;
  cities.sort ();
  print ("ol ==>$ol");
  print ("cities ==>$cities");
}
/ *
Run-time error occurred ↓.
Uncaught Error: Unsupported operation: sort
* /


I was trying to run the sample code and I happened to get the above error.
I don't understand why sample2 gives an error.
I'm told that the sort method is not supported,
I think the sort method can be used when sample1 is working normally.

I'm not sure if I need it, but the source of the sample is
https://medium.com/@davidmorgan_14314/the-mutability-tax-6403d84f21c0
The above is the story of immutables.

  • Answer # 1

    Since const is immutable, it's not surprising that you get an error when you try the destructive method sort ().

    The elements of the list with final can be changed, so it may have been confused with this.

    Reference: A tour of the Dart language --Final and const
    Note: Although a final object cannot be modified, its fields can be changed. In comparison, a const object and its fields cannot be changed: they ’re immutable.
    (The elements of the final object can be changed, but the const object cannot be changed including the elements)