Skip to main content

prefer-trailing-comma

added in: 1.6.0
⚙️🛠
Pro+
preset: recommended

Checks for a trailing comma for arguments, parameters, enum values and collections. By default, warns in cases when items aren't on a single line.

info

If the last item starts on the same line as the opening bracket and ends on the same line as the closing bracket, the rule will not warn about this case.

function('some string', () {
return;
});

⚙️ Config

Set break-on (default is none) to override the default behavior (example).

Set ignored-names (default is empty) to exclude specific instance names from break-on.

analysis_options.yaml
dart_code_metrics:
rules:
- prefer-trailing-comma:
break-on: 2
ignored-names:
- someFn

Example

❌ Bad:

void firstFunction(
// LINT: Prefer adding a trailing comma.
String firstParameter, String secondParameter, String thirdParameter) {
return;
}

void secondFunction() {
firstFunction('some string', 'some other string',
'and another string for length exceed'); // LINT: Prefer adding a trailing comma.
}

void thirdFunction(String someLongVarName, void Function() someLongCallbackName,
String arg3) {} // LINT: Prefer adding a trailing comma.

class TestClass {
void secondMethod() {
thirdFunction('some string', () {
return;
}, 'some other string'); // LINT: Prefer adding a trailing comma.
}
}

final secondArray = [
'some string',
'some other string',
'and another string for length exceed' // LINT: Prefer adding a trailing comma.
];

✅ Good:

void firstFunction(
String firstParameter,
String secondParameter,
String thirdParameter,
) {
return;
}

void secondFunction(String arg1) {
firstFunction(
'some string',
'some other string',
'and another string for length exceed'
);
}

void thirdFunction(String arg1, void Function() callback) {}

void forthFunction(void Function() callback) {}

class TestClass {
void secondMethod() {
thirdFunction('', () {
return;
});

forthFunction(() {
return;
});
}
}

Example with "break-on"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-trailing-comma:
break-on: 2

❌ Bad:

// LINT: Prefer adding a trailing comma.
void firstFunction(String arg1, String arg2) {
return;
}

// LINT: Prefer adding a trailing comma.
void secondFunction(String arg1, String arg2, String arg3) {
return;
}

✅ Good:

void firstFunction(
String arg1,
String arg2,
) {
return;
}

void secondFunction(
String arg1,
String arg2,
) {
return;
}

void thirdFunction(String arg1) {} // Correct, only one parameter