Comments in Dart. Single Line – Multi Line Comment

0
10130
dart comments
how to write comments in dart

Comments are nonexecutable lines of code. Comments are one of the main aspects of any programming language. Like any other programming language, we have comments in Dart too.

Purpose of comments

Comments are used for various purposes.

  • To provide information about project, variable, or an operation.
  • Let the compiler or interpreter to not execute the commented code.

Types of Dart Comments

There are three main types of Dart comments.

  • DO format comments (Single Line comment)
  • Block Comments (Multi Line Comment)
  • Doc Comments

How to write comments in Dart

As we have three different commnet types in Dart. We have different ways to write these comments.

  • Do format comment (//)
  • Block comment (/* ….. */)
  • Doc comment (///)

Best practices for writing comments in Dart

First letter of the comment should be capital unless its a case sensitive identifier. Its true for comments type does not matter if its inline comment, multiline comment or even TODOs.

Please avoid using block for documentation. Good practice

address(address) {
  // Assume address is not null.
  print('Contact him at , $address!');
}

Bad practice

address(address) {
  /* Assume address is not null. */
  print('Contact him at , $address!');
}

Please use /// for doc comments to document member and types. When you use doc comments in place of regular comments it gives you the power of dartdoc. It finds the relevant information and generates the documentation for it. Good practice

///The number of characters in this chunk when unsplit.
int get length => ...

Bad practice

//The number of characters in this chunk when unsplit.
int get length => ...

Here is a dart comment example in action. This code is taken from our Hello world example in Dart.

void main() {
  
  // Below written line will print Dart: Hello World
  print("Dart: Hello World");
  print("I am excited to lean more about dart"); 
  print(15);// Just printing the given number 
  print(15/5);
  print(false);
    
}

Please view this code in dartpad and don’t forget to hit the Run button. You will see the result of every print statement on console but not anything related to comments because they are just used for understanding.

LEAVE A REPLY

Please enter your comment!
Please enter your name here