Take the 2-minute tour ×

Dart has a concept of final. Most dynamic languages don't have this concept.

What is final and what do I use it for?

share|improve this question

1 Answer 1

up vote 21 down vote accepted

final variables can contain any value, but once assigned, a final variable can't be reassigned to any other value.

For example:

main() {
  final msg = 'hello';
  msg = 'not allowed'; // **ERROR**, program won't compile

final can also be used for instance variables in an object. A final field of a class must be set before the constructor body is run. A final field will not have an implicit setter created for it, because you can't set a new value on a final variable.

class Point {
  final num x, y;
  Point(this.x, this.y);

main() {
  var p = new Point(1, 1);
  print(p.x); // 1
  p.x = 2; // WARNING, no such method

It's important to realize that final affects the variable, but not the object pointed to by the variable. That is, final doesn't make the variable's object immutable.

For example:

class Address {
  String city;
  String state;
  Address(this.city, this.state);

main() {
  final address = new Address("anytown", "hi");
  address.city = 'waikiki';
  print(address.city); // waikiki

In the above example, the address variable is marked as final, so it will always point to the object instantiated by the new Address("anytown", "hi") constructor. However, the object itself has state that is mutable, so it's perfectly valid to change the city. The only thing prevented by final is reassigning the address variable.

share|improve this answer
"A final field of a class must be set before the constructor body is run." - This was the part that had been throwing me the most. Even though I was setting the final variable in the constructor it didn't even occur to me that was the reason I was getting the error. –  Kevin Sheehan Jun 18 at 0:36

Your Answer


