Brief Summary : Dart Variable
swimmingkiim
Posted on April 2, 2022
This post may helpful for those who need quick remind of Dart grammar, or a programmer from a different language learning Dart.
Basic
Variables store references.
var
var language = 'dart';
- Mutable variable keyword
By Type
String language = 'dart';
- You can specify the type in order to declare variable.
final & const
final fruits = {
1: 'apple',
2: 'orange'
};
const animals = {
1: 'dog',
2: 'cat'
};
fruits[1] = 'banana'; // NO ERROR
animals[1] = 'monkey'; // ERROR
- There’re similar in sense that they can’t be changed once you assign a value to them.
The Difference Between “final” and “const” keyword
-
final
can’t be changed once you assign a value. -
const
is also like that, but in advance, they require more rules- The value that you’re going to assign should be a
compile-time constant
-
compile-time constant
means a constant value that is already fixed by the time when dart compile process. - For example, String literals that dose not contain interpolated expression and expression must be one of these(null, numeric, string, or boolean)
-
- The value that you’re going to assign should be a
- Also, after assigning a value, variables annotated with
final
can’t be reassigned, but it’s fields can. - Unlike
final
, variables annotated withconst
can’t be reassigned, both itself ant it’s sub fields.
late
late String onlyKnowAfterInitialization;
onlyKnowAfterInitialization = 'hello world';
- Keyword that’s used in below cases.
- You need to assign a value after you declare it.
- You want to use lazy assignment.
- For example, when you need to access
this
in order to assign a value.
- For example, when you need to access
- If the value of a variable annotated with
late
keyword needs to be computed, the computation will not happen unless the variable is actually used in somewhere.
Cheers!
💖 💪 🙅 🚩
swimmingkiim
Posted on April 2, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.