Skip to content

Instantly share code, notes, and snippets.

@chonghorizons
Created November 6, 2021 19:39
Show Gist options
  • Save chonghorizons/20575314f7d2b8aa480c3f021e917c4c to your computer and use it in GitHub Desktop.
Save chonghorizons/20575314f7d2b8aa480c3f021e917c4c to your computer and use it in GitHub Desktop.
Const and Final, Dartpad, samples of what can and cannot be edited, for a String and a Map
// 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.
void main() {
const String name='Howard';
final stats= {'age': 42, 'income': 0};
const unchangeableStats={'hair': "black", "race": "chinese"};
var normalMap= {};
print("My age is ${stats['age']}");
stats['age']=stats['age']!.toInt()+1;
print("My age is ${stats['age']}");
stats['age']=stats['age']!+1;
print("My age is ${stats['age']}");
stats['wisdom']=7; // adding fields to a "final" Map variable is not allowed except for ints. This is okay
print("${stats['wisdom']} wisdom");
// stats['strength']="not much"; // this is not okay. At compile time.
print("${stats['strength']} strength");
print("My race is ${unchangeableStats['race']}");
// unchangeableStats["race"]="global"; // run time error, because i'm trying to change a value pair
// print("My race is ${unchangeableStats['race']}");
print("My name is ${name}");
normalMap["a"]=1;
normalMap["b"]="textGoesHere";
// putting strings or ints into a normal map is fine.
print(normalMap);
// name="SecretAgent"; // compile time error
// print("My new name is ${name}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment