Flutter – Difference Between Final and Const
In the Flutter framework, final
and const
are both used to declare variables that cannot be changed after they are initialized. However, they differ in how they are implemented and when they are evaluated.
final
variables are evaluated at runtime, meaning that their value is not determined until the program is running. This allows final
variables to be different for each instance of a class or object.
const
variables, on the other hand, are evaluated at compile-time, meaning that their value is determined when the code is compiled. Because const
variables are evaluated at compile-time, they must be made up of compile-time constants, such as literals, null
, or references to other const
variables.
Here’s an example of how you might use final
and const
in Flutter:
class MyWidget extends StatefulWidget {
final int someValue;
const MyWidget({Key key, this.someValue}) : super(key: key);
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
static const double _someConstant = 3.14;
@override
Widget build(BuildContext context) {
return Container(
width: widget.someValue * _someConstant,
height: widget.someValue * _someConstant,
);
}
}
In this example, the someValue
field is declared as final
, meaning that it can be set when the MyWidget
object is created, but it cannot be changed after that. The _someConstant
field is declared as static const
, meaning that it is a compile-time constant that is shared by all instances of the _MyWidgetState
class.