Dart Functions

A function in Dart or in any programming language has a specific name and has a set of programming statements. The function can be called at any location of the program to run the statements it has and returns a result, or performs some operations. This process saves time and effort in writing all the function statements one time, then at a certain location of the code call this function by its name to perform a specific procedure or return a value. Also, functions help in organising the program to structured parts which help in program maintenance and any future modifications.

Each function has a unique name which is used to call it inside the Dart program several times without the need to duplicate statements in multiple source code files.Most programming languages come with a prewritten set of functions that are kept in a library.

 

Uses of Functions

The few benefits of the Dart function are given below.

  • Optimises the code.
  • It makes debugging easier.
  • It makes development easy and creates less complexity.
  • It increases the module approach to solve the problems.
  • It enhances the re-usability of the program.
  • We can do the coupling of the programs.

Creating a Function

If you have a number of code statements that need to be used more than once within your program, you can gather them inside a function which has a specific name and then call this function within the program as many times as needed.

Example: In the following example, if you run the following code, the compiler will run the code which is in the main function only.

main() {

}

PrintSomething(){

  print("Hello World!!");

  print("Welcome to i=India");

}

 

Let's understand the general syntax of the defining function.

  • parameter_list - It denotes the list of the parameters, which is necessary when we call a function.
  • return value - A function returns a value after completing its execution.
  • return_type - It can be any data type such as void, integer, float, etc. The return type must be matched with the returned value of the function.
  • func_name - It should be an appropriate and valid identifier.

Example - 1

void main() {  

  print("Example of multiply two number using the function");    

  // Creating a Function  

  

  int sum(int a, int b){  

            // function Body  

            int result;  

            result = a*b;  

            return result;  

}  

// We are calling a function and storing a result in variable c  

var c = multiply(5,6);  

print("The sum of two numbers is: ${c}");  

 

Output

Example of add two number using the function

The sum of two numbers is: 30


Advertisements