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.
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.
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