Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Dart Constants

In Dart, const is used to declare compile-time constants. Constants declared with const are evaluated at compile-time, allowing Dart to optimize their usage. Here are a few key points about const in Dart:


Compile-time Evaluation: When you declare a variable or object as const, its value must be known at compile-time. This means that you can only assign literals or other const variables to a const variable.

const int x = 5;
const String name = 'John';



Immutable: Constants declared with const are immutable, meaning their values cannot be changed once they are assigned.

const int x = 5;
// This will cause a compilation error
x = 10;



Benefits: Using const can lead to better performance in your Dart code because the values are known at compile-time and can be optimized accordingly. It also helps ensure that certain values remain constant throughout the execution of your program.

Const Constructors: In Dart, you can declare constructors as const. This means that instances of the class created with a const constructor will also be considered const

class Point {
final int x;
final int y;
const Point(this.x, this.y);
} void main() {
const p1 = Point(1, 2);
// This will cause a compilation error
p1.x = 5;
}


Const Collections: Dart allows you to create constant lists, sets, and maps using the const keyword. These collections are immutable and their values must be known at compile-time.

const List< int> numbers = [1, 2, 3];
const Set< String> names = {'Alice', 'Bob', 'Charlie'};
const Map< String, int> scores = {'Alice': 100, 'Bob': 90, 'Charlie': 80};






Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java