Skip to main content

avoid-global-state

added in: 1.6.0
Free+

Warns when a global mutable variables is used.

Having many mutable global variables inside an application is a pretty bad practice:

  • application state becomes distributed between multiple files
  • application state is not protected: it can be modified in almost any place
  • it might be hard to debug such applications

So the common practice is to use state management solutions instead of mutable global variables.

Example

❌ Bad:

// LINT: Avoid global variables without the 'const' or 'final' keyword. Try removing it or making immutable.
var answer = 42;

// LINT: Avoid global variables without the 'const' or 'final' keyword. Try removing it or making immutable.
var evenNumbers = [1, 2, 3].where((element) => element.isEven);

class Foo {
// LINT: Avoid global variables without the 'const' or 'final' keyword. Try removing it or making immutable.
static int? bar;
}

✅ Good:

const answer = 42; // Correct, immutable value
final evenNumbers = [1, 2, 3].where((element) => element.isEven); // Correct, final declaration

class Foo {
static int _bar = 42; // Correct, private
}

Additional Resources