Dart Defined Constant using final and const keyword

Jinali GhoghariJinali Ghoghari
1 min read

1. final in Dart:

* Use final when you want to create a variable that can only be assigned a value once.

* The value is determined at runtime, but once assigned, it cannot be changed.

Example:

final int myNumber = 42; // myNumber can only be set once.

2. constin Dart:

* Use const when you want to create a variable whose value is known at compile-time.

* The value must be a compile-time constant, such as a number or a string literal.

* const variables are implicitly final but also have additional restrictions on the type of values they can hold.

Example:

const double piValue = 3.14159; // piValue is a compile-time constant.

In simpler terms, final is for values known at runtime that won't change, and const is for values known at compile-time that are constant throughout the program. Use final for situations where the value is determined dynamically, and use const when the value is known at compile-time and will never change.

0
Subscribe to my newsletter

Read articles from Jinali Ghoghari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jinali Ghoghari
Jinali Ghoghari