Const vs Final in Flutter / Dart
In Flutter, final
and const
are both used to declare variables that cannot be reassigned.
final
variables are evaluated at runtime and can only be set once. They are often used when the value of a variable needs to be determined at runtimes, such as when it is based on user input or the result of a function.
const
variables, on the other hand, are evaluated at compile-time and must be known at the time the code is written. They are often used for values that will not change, such as constants or hard-coded values.
Here are some key differences between final
and const
in Flutter:
final
variables are evaluated at runtime, whileconst
variables are evaluated at compile-time.final
variables can only be set once, whileconst
variables cannot be set at all.final
variables can be different for each object, whileconst
variables are the same for all objects.final
variables are slower to access thanconst
variables, since they are evaluated at runtime.
In general, you should use final
variables when you need to set a value at runtime and const
variables when you need to use a constant value that is known at compile-time.
Here is an example of how final
and const
can be used in Flutter:
final int x = 42; // x is a final variable whose value is evaluated at runtime
final int y = calculateValue(); // y is a final variable whose value is determined when it is first accessed
const int a = 42; // a is a const variable whose value is evaluated at compile-time
const int b = calculateValue(); // This will cause an error because calculateValue() is not a compile-time constant
In general, you should use const
variables when possible because they are more efficient and can be evaluated at compile time. However, if you need to declare a variable that cannot be reassigned and whose value is not known at compile-time, you can use the final
keyword.
Thank you for reading! Cheers!!