Functions in Dart

Function In Dart

Functions are the block of code that takes input, performs a specific task and gives the result. They are created when some statements are repeatedly occuring in the program. The function will avoid repetition in your code. Function makes it easy to divide the complex program into smaller parts and increase the reusability of the code in program. The main objective of function is DRY(Don’t Repeat Yourself).

Input => Function => Output

Syntax

return_type function_name(parameter1,parameter2, ...){
  // function body
}

Return type: It tells you what is the type of function output. It can be void, String, int, double, etc. If the function doesn’t return anything, you can use void as the return type.

Function Name: You can name functions by almost any name. Always follow a lowerCamelCase naming convention like void printName().

Parameters: Parameters are the input to the function which you can write inside the bracket (). Always follow a lowerCamelCase naming convention for your function parameter.

Example Of Function In Dart

Here, function return type is void, and function name is printName(). This function has no parameter and no return type. This program simply print the function printName().

Example

void printName(){
  print("My name is Raj Sharma. I am from function.");
}
void main(){
  printName();
}
Show Output

Other Example Of Function In Dart

This function finds the sum of two numbers. Here, function accepts two parameters. i.e., num1 and num2, and the return type is void.

Example

 void add(int num1, int num2){
  int sum = num1 + num2;
   print("The sum is $sum");
}

void main(){
  add(10, 20);
}
Show Output

Optional Positional Parameter In Dart

You can write optional positional parameter in dart using a square bracket []. It means you are allow to give some optional parameters inside the function as well as you don’t have to use it compulsory. It can be the option.

Example

 void add(int num1, int num2, [int? num3]){
   int sum;
   if(num3 != null){
     sum = num1 + num2 + num3;
   }else{
     sum = num1 + num2;
   }
   
   print("The sum is $sum");
}

void main(){
  add(10, 20, 40);
}
Show Output