Skip to main content

prefer-trailing-comma

added in: 1.0.0 style

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.

Can be configured with break-on option, which additionally enables checks for given amount of items. For example, if break-on is equal 2, then the rule also warns for all functions with 2 or more parameters (if they have no trailing comma).

info

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

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

Config

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

dart_code_linter:
...
rules:
...
- prefer-trailing-comma:
break-on: 2

Example

Bad:

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

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

void thirdFunction(String someLongVarName, void Function() someLongCallbackName,
String arg3) {} // LINT

class TestClass {
void firstMethod(
String firstParameter, String secondParameter, String thirdParameter) { // LINT
return;
}

void secondMethod() {
firstMethod('some string', 'some other string',
'and another string for length exceed'); // LINT

thirdFunction('some string', () {
return;
}, 'some other string'); // LINT
}
}

final secondArray = [
'some string',
'some other string',
'and another string for length exceed' // LINT
];

final secondSet = {
'some string',
'some other string',
'and another string for length exceed' // LINT
};

final secondMap = {
'some string': 'and another string for length exceed',
'and another string for length exceed': 'and another string for length exceed' // LINT
};

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 firstMethod(
String firstParameter,
String secondParameter,
String thirdParameter,
) {
return;
}

void secondMethod() {
firstMethod(
'some string',
'some other string',
'and another string for length exceed',
);

thirdFunction('', () {
return;
});

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

With given config:

- break-on: 2

Bad:

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

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

Good:

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

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

enum FirstEnum { firstItem }

const instance = FirstClass(
0,
0,
0,
);