thumbnail

Comments in Dart

Published on 29 March 2020
Last Updated on 29 March 2020

What are comments in Dart

Documentation comments are used for generating documentations by Dart tool-chain. Comments are used for making the source code of the program more human readable. Comments are used for giving instructions to the programmer.

Types of comments in Dart

Dart supports following 3 types of comments

  • Single line comments.
  • Multi line comments.
  • Documentation comments,(single line and multi-line)

Single line comments in Dart

In Dart, Single line comments are a set of statements that are ignored by the compiler. Single line comments begin with //, everything after // till the end of the line is ignored by the dart compiler.

Program given below demonstrates how to define single line comments in Dart.

// program to demonstrate single line comments in Dart

int add(int a, int b) {
  // This is a sigle line comment, line given below returns addition of two numbers
  return a + b;
}

main(List<String> args) {
  print(add(3, 4));
}

Above program produces following output:

7

Multi line comments

Similar to single line comments, multi line comments are ignored by the Dart compiler and they are used for commenting out multiple lines at once.

Multi line comments in Dart are used for commenting out multiple lines in Dart. Multi-line comments.

Multi-line comments begin with /* and end with */.

Program that makes use of multi line comments:

// multiline comments in Dart

int sub(int a, int b) {
  /*
  This is a multi line comment
  There is a bug in this function.
  This function returns addition of two numbers instead of returning subtraction of two numbers.
  Fix this!
   */
  return a + b;
}

main(List<String> args) {
  print(sub(3, 4));
}

Above program produces following output:

7

Documentation comments in Dart

Documentation comments are used by Dart tool chain for generating documentations for functions methods classes and more.

Content inside a documentation comments are completely ignored unless there is bracket symbol used. Brackets inside documentation comments are used for referring to specific classes methods fields or top level variable and functions ad parameters. Names specified in brackets are resolved in lexical scope of the documented program element.

Program that makes use of documentation comments in Dart:

// program to demonstrate documentation comments in Dart

/// this is a documentation comment
/// this function returns addition of two numbers a and b
/// both a and b must be integers
int add(int a, int b) {
  return a + b;
}

/** this is a multiline documentation comment
    this function returns subtraction of two number a and b
    both a and b must be integers **/
int sub(int a, int b) {
  return a - b;
}

main(List<String> args) {
  print(add(3, 4));
  print(sub(3, 4));
}

Above program produces following output:

7
-1