Functions in dart

Learning Objectives

  1. To understand what Functions are

  2. To understand the composition of functions

  3. Be able to understand types of functions in Dart

FUNCTIONS

In this tutorial, you will learn about functions in dart. Functions are the block of code that performs a specific task. They are created when some statements are repeatedly occurring in the program. The function helps reusability of the code in the program.

Function Advantages

  • Avoid Code Repetition

  • Easy to divide the complex program into smaller parts

  • Helps to write a clean code

Syntax of a function

returntype functionName(parameter1,parameter2, ...){

// function body

}

Return type: It tells you the function output type. 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 1: Function That Prints Name

This is a simple program that prints name using function. The name of function is printName().

// Function to print name
void printName() {
  print("My name is Mariam");
}

void main() {
  // Calling the function
  printName();
}

Example 2: Function To Find Sum of Two Numbers

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

// Function to find the sum of two numbers
void findSum(int num1, int num2) {
  int sum = num1 + num2;
  print("The sum of $num1 and $num2 is: $sum");
}

void main() {
  // Calling the function with two numbers
  findSum(10, 20);
}

Key Points

  • In dart function are also objects.

  • You should follow the lowerCamelCase naming convention while naming function.

  • You should follow the lowerCamelCase naming convention while naming function parameters.

Types Of Functions

Functions are the block of code that performs a specific task. Here are different types of functions:

  • No Parameter And No Return Type

  • Parameter And No Return Type

  • No Parameter And Return Type

  • Parameter And Return Type

Function With No Parameter And No Return Type

In this function, you do not pass any parameter and expect no return type. Here is an example of it:

printName() is a function which prints name on your screen.

// No parameter and no return type
void main() {
  printName();
}

//no parameters and no return type (nothing in parameter list and no return type)
void printName() {
  print("Aron Jackson is a student ");
}

Function With Parameter And No Return Type

In this function, you do pass the parameter and expect no return type. Here is an example of it:

//Here printFullName is a function  With a parameter and no return type function that takes the name of the parameter
void main() {
  printName("Aron Jackson");
}

// parameters and no return type
void printName( String name ) {
  print("My name is $name ");
}

In this program, printName(String name) is the function which has keyword void. It means it has no return type, and the pair of parentheses is not empty but this time that suggests it to accept a parameter.

Function With No Parameter And Return Type

In this function, you do not pass any parameter but expect return type. Here is an example of it:

Here InstructorName() is a function which returns Instructor's name. In the entire program, anyone can use this function to find the name of the Instructor

// Function to return Instructor's name
String InstructorName() {
  return "Allan";
}

void main() {
  // Calling the function and storing the result
  String instructor = InstructorName();

  // Printing the instructor's name
  print("The Instructor's name is: $instructor");
}

In this program, InstructorsName() is the function which has String keyword before function name, means it return String value, and the empty pair of parentheses suggests that there is no parameter that is passed to the function.

Function With Parameter And Return Type

In this function, you do pass the parameter and also expect return type. Here is an example of it:

// Function to add two integers and return the result
int add(int a, int b) {
  return a + b;
}

void main() {
  // Calling the function with two integers
  int result = add(10, 20);

  // Printing the result
  print("The sum of 10 and 20 is: $result");
}

In this program, int add(int a, int b) is the function with int as the return type, and the pair of parenthesis has two parameters, i.e., a and b.

THE TYPES OF FUNCTIONS DISCUSSED

The code snippets below indicate all the functions. Use the comments as your guidelines.

void main() {
  // Calling the functions and displaying their outputs

  // Function with no parameters and no return type
  printWelcomeMessage();

  // Function with parameters and no return type
  greetUser("Alice");

  // Function with parameters and return type
  int sumResult = add(10, 20);
  print("The sum of 10 and 20 is: $sumResult");

  // Function with no parameters but expects a return type
  String instructorName = InstructorName();
  print("The instructor's name is $instructorName");

  // Function with parameters and return type
  int productResult = multiply(5, 6);
  print("The product of 5 and 6 is: $productResult");
}

// Function with no parameters and no return type
void printWelcomeMessage() {
  print("Welcome to the Dart programming tutorial!");
}

// Function with parameters and no return type
void greetUser(String name) {
  print("Hello, $name! Welcome to Dart.");
}

// Function with parameters and return type
int add(int a, int b) {
  return a + b;
}

// Function with no parameters but expects a return type
String InstructorName() {
  return "Allan";
}

// Function with parameters and return type
int multiply(int a, int b) {
  return a * b;
}

Explanation:

  • printWelcomeMessage(): Prints a welcome message. No parameters and no return type.

  • greetUser(String name): Prints a greeting message using the provided name. Takes one parameter and has no return type.

  • add(int a, int b): Returns the sum of two integers. Takes two parameters and returns an int.

  • InstructorName(): Returns a fixed string, the instructor's name. No parameters and returns a String.

  • multiply(int a, int b): Returns the product of two integers. Takes two parameters and returns an int.

Anonymous Functions

In the previous lesson we introduced you to functions that are defined by using a function name like main(), fullName(). In this lesson we will talk about nameless functions or functions without a name. This type of function is known as an anonymous function, lambda, or closure. An anonymous function behaves the same as a regular function, but it does not have a name with it. It can have zero or any number of arguments / parameters with an option type annotation.

Syntax

Below is the syntax of the anonymous function

Knowledge Panel:

  • You can assign an anonymous function to a variable

  • You can pass an anonymous function as a parameter / argument

Example 1:

In this example, you will learn to use an anonymous function to print all list items. This function invokes each fruit without having a function name.

void main() {
  // List of fruits
  var fruits = ['Apple', 'Banana', 'Cherry', 'Date'];

  // Using an anonymous function with forEach to print each fruit
  fruits.forEach((fruit) {
    print(fruit);
  });
}

Explanation:

  • var fruits = ['Apple', 'Banana', 'Cherry', 'Date'];: Defines a list of fruits.

  • fruits.forEach((fruit) { ... });: The forEach method is used to iterate over each item in the list. It takes an anonymous function as its argument.

    • (fruit) { print(fruit); }: This is an anonymous function (a function without a name) that takes one parameter fruit and prints it.

Example 2:

In this example, we will use an anonymous function to print all list items.

void main() {
  // List of items
  var items = ['Laptop', 'Tablet', 'Smartphone', 'Smartwatch'];

  // Using an anonymous function with forEach to print each item
  items.forEach((item) {
    print(item);
  });
}

Explanation:

  • var items = ['Laptop', 'Tablet', 'Smartphone', 'Smartwatch'];: Defines a list of items.

  • items.forEach((item) { ... });: The forEach method iterates over each element in the list and applies the provided anonymous function.

    • (item) { print(item); }: This is an anonymous function that takes one parameter item and prints it.
  • Arrow Function

    If you want to declare a function in one line; In Dart we have a fat arrow function that can enable you. The function is represented by \=> symbol.

    Syntax

    Below is the syntax for the arrow function

    Knowledge Panel

    Note: The arrow function is used to make your code short. => expr syntax is a shorthand for { return expr; }.

  • Here's a very short code sample that demonstrates how to declare and use a fat arrow function in Dart:

      void main() {
        // Fat arrow function to add two numbers
        int add(int a, int b) => a + b;
    
        // Calling the function
        print(add(5, 3)); // Output: 8
      }
    

    In this example, the function add takes two integers a and b, and returns their sum using the fat arrow syntax =>.

    Calculation of simple interest without Arrow Function

    This program finds simple interest without using the arrow function.

      void main() {
        // Principal amount, rate of interest, and time period
        double principal = 1000.0;
        double rate = 5.0;
        double time = 3.0;
    
        // Function to calculate simple interest
        double calculateSimpleInterest(double p, double r, double t) {
          return (p * r * t) / 100;
        }
    
        // Calling the function and storing the result
        double interest = calculateSimpleInterest(principal, rate, time);
    
        // Printing the result
        print("The simple interest is: \$${interest}");
      }
    

    Calculation of simple interest WITH Arrow Function

      void main() {
        // This is the main function, the entry point of every Dart program.
        // Code inside main() is what gets executed when you run the program.
    
        double principal = 1000.0;
        // This declares a variable 'principal' of type double (decimal number).
        // 'principal' represents the initial amount of money you are working with.
    
        double rate = 5.0;
        // This declares another double variable 'rate' that represents the interest rate.
    
        double time = 3.0;
        // This declares a double variable 'time', which represents the time period (in years).
    
        // Declaring a function using the 'arrow function' syntax.
        // The function 'calculateSimpleInterest' takes three double arguments: p, r, t.
        // It calculates the simple interest using the formula (p * r * t) / 100.
        double Function(double, double, double) calculateSimpleInterest = (p, r, t) => (p * r * t) / 100;
    
        // This line calls the 'calculateSimpleInterest' function with the values of principal, rate, and time.
        // The result is stored in the 'interest' variable.
        double interest = calculateSimpleInterest(principal, rate, time);
    
        // This prints the result (the calculated interest) to the console.
        // '\$${interest}' formats the interest value as a part of the string.
        print("The simple interest is: \$${interest}");
      }