Rules / Style / prefer-first

prefer-first

lint/style/prefer-first
recommended
Same as prefer-first · Dart Code Metrics

Flags [0] index access that should use the .first getter.

Reading the leading element as xs.first states the intent directly and is easier to read than the numeric xs[0], which forces the reader to recognize that zero means "first". The rule matches an index expression whose subscript is the integer literal 0; any other index, including a non-literal expression that evaluates to zero, is left alone. Matching is syntactic on the literal, so it does not confirm the receiver exposes a first getter.

Invalid

example.dartdart
// Bad: using [0] instead of .first
void example() {
  final items = [1, 2, 3];
  final first = items[0];
  print(first);
}

class Processor {
  String getFirstName(List<String> names) {
    return names[0];
  }

  void processHead(List<int> values) {
    final head = values[0];
    if (head > 0) {
      compute(head);
    }
  }
}

void multipleViolations(List<String> items) {
  final a = items[0];
  final b = items[0].length;
  print('$a $b');
}
Prefer .first over [0] to access the first element
3 final items = [1, 2, 3];
4 final first = items[0];
Prefer .first over [0] to access the first element
9 String getFirstName(List<String> names) {
10 return names[0];
Prefer .first over [0] to access the first element
13 void processHead(List<int> values) {
14 final head = values[0];
Prefer .first over [0] to access the first element
21void multipleViolations(List<String> items) {
22 final a = items[0];
Prefer .first over [0] to access the first element
22 final a = items[0];
23 final b = items[0].length;

Valid

example.dartdart
// Good: using .first
void example() {
  final items = [1, 2, 3];
  final first = items.first;
  print(first);
}

class Processor {
  String getFirstName(List<String> names) {
    return names.first;
  }

  void processHead(List<int> values) {
    final head = values.first;
    if (head > 0) {
      compute(head);
    }
  }
}

void multipleAccess(List<String> items) {
  final a = items.first;
  final b = items.first.length;
  print('$a $b');
}

// OK: accessing non-zero indices
void accessOther(List<int> items) {
  final second = items[1];
  final third = items[2];
}

// OK: in loop context
void loopAccess(List<List<int>> matrix) {
  for (int i = 0; i < matrix.length; i++) {
    final row = matrix[i]; // accessing by variable index is OK
  }
}

How to configure

Set the severity of prefer-first in your falcon.json:

falcon.jsonjson
{
  "linter": {
    "rules": {
      "style": {
        "prefer-first": "error"
      }
    }
  }
}