What is the "const" keyword used for in Dart?
const
means compile time constant. The expression value must be known at compile time. const
modifies "values".
From news.dartlang.org,
"const" has a meaning that's a bit more complex and subtle in Dart. const modifies values. You can use it when creating collections, like const [1, 2, 3], and when constructing objects (instead of new) like const Point(2, 3). Here, const means that the object's entire deep state can be determined entirely at compile time and that the object will be frozen and completely immutable.
if you use
const x = 5
then variable x can be used in a cosnt collection like
const aConstCollection = const [x];
if you don't use const
, and just use x = 5
then
const aConstCollection = const [x];
is illegal.
More examples from www.dartlang.org
class SomeClass {
static final someConstant = 123;
static final aConstList = const [someConstant]; //NOT allowed
}
class SomeClass {
static const someConstant = 123; // OK
static final startTime = new DateTime.now(); // OK too
static const aConstList = const [someConstant]; // also OK
}
Here are some facts about const
values:
The value must be known at compile time.
const x = 5; // OK
Anything that is calculated at runtime can't be
const
.const x = 5.toDouble(); // Not OK
A
const
value means that it's deeply constant, that is, every one of its members is constant recursively.const x = [5.0, 5.0]; // OK const x = [5.0, 5.toDouble()]; // Not OK
You can create
const
constructors. That means that it is possible to createconst
values from the class.class MyConstClass { final int x; const MyConstClass(this.x); } const myValue = MyConstClass(5); // OK
const
values are canonical instances. That means that there is only a single instance no matter how many you declare.main() { const a = MyConstClass(5); const b = MyConstClass(5); print(a == b); // true } class MyConstClass { final int x; const MyConstClass(this.x); }
If you have a class member that is
const
, you must also mark it asstatic
.static
means it belongs to the class. Since there is only ever one instance ofconst
values, it wouldn't make sense for it to not bestatic
.class MyConstClass { static const x = 5; }
See also
- Dart Const Tutorial – All You Need to Know (Const Expressions, Canonical Instances and More)