Created
November 6, 2021 19:39
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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