This is a concise article about commenting in Flutter and Dart.
Single-Line Comment (Format Comment)
Just put two slash symbols at the beginning of the line you want to comment out.
// This is a comment
print('abc');
Multi-Line Comment (Block Comment)
Syntax:
/* ... */
This method is usually used to comment out a block of code, like this:
/*
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Kindacode.com'),
),
body: Center(),
);
}
}
*/
DOC Comment
Using DOC comment allows the dartdoc library to automatically generate documentation for your code based on the content of your comments.
Example:
/// Deletes the file at [path].
/// Throws an [IOError] if the file could not be found.
Using hotkeys in Visual Studio Code
If you are using Visual Studio Code, you can comment out a single line or a block of code by using keyboard shortcuts. Just select the lines you want to make comments with your mouse, then press the following key combination:
- Ctrl + K then press Ctrl + C if you’re using Windows
- Command + K then press Command + C if you’re on a Mac
To uncomment a block of code, use your mouse to select it and then use the following key combination:
- Ctrl + K then Ctrl + U if you’re on Windows
- Command + K then Command + U if you’re on a Mac
You can also hit Ctrl + / (Windows), Command + / (Mac) to toggle comments.
Demo:
Conclusion
You’ve learned some useful ways to make comments in Dart and Flutter. This can help you make the code more readable and understandable for other programmers or your future self, or prevent the execution of some code when testing or debugging, or whatever purpose we can think about.
If you’d like to explore more new and interesting stuff about Dart and Flutter, consider taking a look at the following articles:
- Flutter SliverList – Tutorial and Example
- How to Create a Countdown Timer in Flutter
- How to remove items from a list in Dart
- How to implement Star Rating in Flutter
- Flutter ConstrainedBox – Tutorial and Examples
- How to use Cupertino icons in Flutter
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.