Sat, Dec 17, 2022
Read in 2 minutes
In this post we take a look at "const" keyword with some example codes.
In Dart, const
is a keyword that is used to declare variables and values that are compile-time constants. A compile-time constant is a value that can be determined at compile time and is never changed at runtime.
Here’s an example of declaring a const
variable in Dart:
const int x = 10;
In this example, we declare a const
integer variable named x
with the value of 10
. Because x
is a compile-time constant, its value is determined at compile time and cannot be changed at runtime.
const
can also be used to create immutable data structures like lists and maps:
const List<int> numbers = [1, 2, 3];
const Map<String, int> scores = {'Alice': 100, 'Bob': 90, 'Charlie': 80};
In this example, we declare a const
list of integers named numbers
and a const
map from strings to integers named scores
. Because these data structures are declared as const
, their contents cannot be changed at runtime.
One important thing to note about const
is that it can only be used with values that can be determined at compile time. For example, if you try to create a const
variable using a value that is determined at runtime, you will get a compile-time error. Here’s an example of what not to do:
// This code will cause a compile-time error!
int x = 10;
const int y = x;
In this code, we try to create a const
integer variable named y
using the value of the non-const
variable x
. Because x
is not a compile-time constant, we get a compile-time error.
In summary, const
is a keyword in Dart that is used to declare compile-time constants, which are values that can be determined at compile time and are never changed at runtime. const
can be used to create immutable data structures like lists and maps, and can help to ensure that your code is correct and efficient.