An awesome linter rule that saves me a ton of time and keeps code consistent throughout my codebases is require_trailing_commas
.
“DO use trailing commas for all function calls and declarations unless the function call or definition, from the start of the function name up to the closing parenthesis, fits in a single line.” - Dart Docs
When you combine this linter rule with formatting your code on save, it’ll speed up your productivity!
To add this linter rule, go into the analysis_options.yaml
and add it to the rules
section.
// analysis_options.yaml
linter:
rules:
- require_trailing_commas
We can test this out by pasting the following code into a dart
file.
// Before
class User {
User({required this.name,
required this.email, required this.age}); // <- Missing comma
final String name;
final String email;
final int age;
}
class Fun extends StatelessWidget {
const Fun({super.key});
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: Colors.red, borderRadius: BorderRadius.circular(10)), // <- Missing comma
child: Text('Hello World'),
);
}
}
Once we format with Ctrl/Alt + Shift + F
or save our file with format on save, our code is updated with commas added to the proper locations.
// After
class User {
User({
required this.name,
required this.email,
required this.age, // <- New comma
});
final String name;
final String email;
final int age;
}
class Fun extends StatelessWidget {
const Fun({super.key});
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(10), // <- New comma
),
child: const Text('Hello, world!'),
);
}
}