Skip to content

Instantly share code, notes, and snippets.

@JoeCodeswell
Last active July 14, 2020 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoeCodeswell/e31c87278033dbaf3bb4d55bfa8fd721 to your computer and use it in GitHub Desktop.
Save JoeCodeswell/e31c87278033dbaf3bb4d55bfa8fd721 to your computer and use it in GitHub Desktop.
Dart Final vs. Const
// https://dartpad.dev/e31c87278033dbaf3bb4d55bfa8fd721
// e31c87278033dbaf3bb4d55bfa8fd721
// [Dart Final vs. Const](https://www.appbrewery.co/courses/548873/lectures/9988849)
void main() {
// int myNumber = 1; // if we want no change after this
// use `const` OR `final`
// const int myConst = 2;
// final int myFinal = 3;
// myConst = 4; // error Constant variables can't be assigned a value - docs "a compile-time constant"
// myFinal = 5; // error The final variable 'myFinal' can only be set once
// myNumber = 6;
// print('$myNumber, $myConst, $myFinal'); // 6, 2, 3
// diffs between [Final and const](https://dart.dev/guides/language/language-tour#final-and-const)
final DateTime myFinal = DateTime.now(); // OK runtime
print('$myFinal'); // OK runtime 2020-07-14 09:54:57.315
/*
const DateTime myConst = DateTime.now(); // BEFORE run-time compiler says 2 errors: e1 The constructor being called isn't a const constructor - e2 Const variables must be initialized with a constant value
print('$myConst'); // OK runtime 2020-07-14 09:54:57.315
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment