Rules / Correctness / avoid-mutable-global-variables

avoid-mutable-global-variables

lint/correctness/avoid-mutable-global-variables
recommended
Same as avoid_mutable_global_variables · Pyramid Lint

Disallow mutable top-level variables.

Flags a top-level variable that is neither const nor final. A mutable global can be reassigned from anywhere in the program, so its value at any moment depends on execution order that no local reading of the code reveals — a recurring source of subtle bugs and flaky, order-dependent tests. Declare it const or final; when a value genuinely must change over time, hold it in an object with a clear owner rather than a free-floating global.

Invalid

example.dartdart
/// Mutable top-level variable
var items = <String>[];

/// Mutable int at top-level
int count = 0;

/// Mutable list at top-level
List<int> numbers = [1, 2, 3];

/// Mutable map at top-level
Map<String, String> config = {'key': 'value'};

/// Late top-level variable that is neither final nor const
late String sharedState;

class MyClass {
  void example() {
    print(items);
  }
}
Avoid mutable global variables. Use const or final instead.
1/// Mutable top-level variable
2var items = <String>[];
Avoid mutable global variables. Use const or final instead.
4/// Mutable int at top-level
5int count = 0;
Avoid mutable global variables. Use const or final instead.
7/// Mutable list at top-level
8List<int> numbers = [1, 2, 3];
Avoid mutable global variables. Use const or final instead.
10/// Mutable map at top-level
11Map<String, String> config = {'key': 'value'};
Avoid mutable global variables. Use const or final instead.
13/// Late top-level variable that is neither final nor const
14late String sharedState;

Valid

example.dartdart
/// A final top-level variable is not flagged (only const/final skips).
final RegExp kPattern = RegExp(r'[a-z]+');

/// A final top-level list initialised from a call is still final, so allowed.
final List<int> kComputed = List<int>.generate(3, (i) => i);

/// Const top-level variable
const List<String> kItems = <String>[];

/// Const int at top-level
const int kCount = 0;

/// Const regex pattern
const String kPatternString = r'[a-z]+';

/// Const list at top-level
const List<int> kNumbers = [1, 2, 3];

/// Const map at top-level
const Map<String, String> kConfig = {'key': 'value'};

/// Const string
const String kSharedState = '';

/// Class with mutable state
class MyClass {
  /// Instance fields can be mutable
  late String instanceState;

  /// Private instance field
  final List<String> _items = [];

  /// Const field in class (no instance state)
  static const String kClassName = 'MyClass';

  void example() {
    print(kItems);
  }
}

How to configure

Set the severity of avoid-mutable-global-variables in your falcon.json:

falcon.jsonjson
{
  "linter": {
    "rules": {
      "correctness": {
        "avoid-mutable-global-variables": "error"
      }
    }
  }
}