The `Final` Keyword in Dart

The `Final` Keyword in Dart

When to use the final keyword?

The final keyword in Dart is used when we don't know the value at compile time, however, we know that the value will be available at runtime.

The final variables once initialized cannot be mutated as in reassigned. However, the values/objects held by the variable can be modified.

Let's see an example.

class User {
  String name;
  int age;

  User(this.name, this.age);

  @override
  String toString() {
    return "$name: $age";
  }
}

void main() {
  final users = <User>[User("Amit", 32), User("Rahul", 26)];

  users.add(User("Bob", 98));

  print(users[0]); // Bob: 98

  //mutable: final fields objects can be changed
  users[0] = User("Kevin", 18);
  print(users[0]); // Kevin: 18

  //mutable: final fields object's value can be changed
  users[0].name = "What's there in the name? ";
  print(users[0]); // What's there in the name?: 18

  //immutable: a final variable cannot be modified
  users = <User>[
    User("Ronaldo", 33)
  ]; // COMPILE-TIME  Can't assign to the final variable 'users'.
}

What to consider when confused?

  • The final variable can only be set once at runtime
  • A final object cannot be modified, its object's values can be changed as we saw above.

Now we know when to use const and final keywords with variables in Dart See When to use const keyword in Dart? if you haven't seen it already.

Next, we will look at a special keyword in Dart and the details around it?

Next => Sound Null safety in Dart.

Did you find this article valuable?

Support Amit Acharya by becoming a sponsor. Any amount is appreciated!