When declaring variables in Dart, prefer const over final over var:

  • const is for hardcoded, compile-time constants
  • final is for read-only variables that are set just once
  • var is for variables that are set more than once

The static analyzer will help you choose wisely. 🙂

Example:

void main() {
  // compile-time constant
  const favourite = 'I like pizza with tomatoes';
  // read-only variable, set just once
  final newFavourite = favourite.replaceAll('pizza', 'pasta');
  // read/write variable, set more than once
  var totalSpaces = 0;
  for (var i = 0; i < newFavourite.length; i++) {
    final c = newFavourite[i];
    if (c == ' ') {
      totalSpaces++;
    }
    print('Counted $totalSpaces spaces');
  }
}