5. Dart Functions

Functions in Dart

Functions are the buidling blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once the functions are defined they need to be called to access a block of code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code. A function definition provides the actual body of the function. You can pass datat, known as parameters, into a function. A function can return a data as a result.

Function Description
Defining a Function A function definition specifies what and how a specific task would be done.
Calling a Function A function must be called so as to execute it.
Returning Functions Functions may also return value along with control, back to the caller.
Parameterized Function Parameters are mechanism to pass values to functions.

Recursive Dart Function and Lambda Function are the functions in Dart.

Recursive Dart Functions

Recursion is the technique that iterates over an operation by calling itself until all the results have been arrived. It is best for function repetition with diffrent paramters within a loop.

Example

void main(){
  print(factorial(7));
}
factorial(num){
  if(num > 0){
    return(num*factorial(num-1)); // function invokes itself
  }
  else{
    return 1;
  }
}

output

5040

Lambda Functions

These functions are a consile mechanism to represent functions. They are also called Arrow Functions. Syntax

[return_type]function_name(parameters)=>expression;

Example

void main(){
  msg();
  print(test());
}
msg()=> print("hello");
int test()=>43;

output

hello
43

You will learn more about how to define function, call a function and how to use paramters.