Dart Basic- Functions

Home /

Table of Contents

Functions in Dart


Functions are a set of statements that are used to perform specific tasks. In Dart, functions are objects of type Function, which means that they can be assigned to variables, passed as arguments to other functions, and returned from other functions. In this tutorial, we’ll go through everything you need to know about functions in Dart.

Declaring Functions


The basic syntax for declaring a function in Dart is as follows:

return_type function_name(parameters) {
// function body
}


Here’s what each part of the syntax means:

  • return_type: This is the type of value that the function will return. If the function doesn’t return anything, you can use the special void type.
  • function_name: This is the name of the function. It should be descriptive of what the function does.
  • parameters: These are the inputs to the function. They are optional, and you can have as many or as few as you like. If you have more than one parameter, separate them with commas.
  • function_body: This is the set of statements that make up the function. It is enclosed in curly braces {}.

Here’s an example of a simple function that takes two integers as input and returns their sum:

int addNumbers(int a, int b) {
    return a + b;
}


Calling Functions

To call a function, you simply use its name and provide any required inputs:

var result = addNumbers(3, 5);
print(result); // Output: 8

In this example, we call the addNumbers function with inputs 3 and 5. The function returns the sum of the inputs, which is 8. We store the result in a variable called result and then print it to the console.

Optional Parameters


Sometimes you want to create a function that can take a variable number of arguments. In Dart, you can achieve this using optional parameters. Optional parameters can be positional or named.

Positional Parameters


Positional parameters are declared inside square brackets []. When calling a function with positional parameters, you can provide as many or as few arguments as you like, as long as you provide them in the order that they are declared.

Here’s an example of a function that takes two required parameters and one optional parameter:

void greet(String name, String greeting, [String? exclamation]) {
    String message = '$greeting, $name';
    if (exclamation != null) {
        message = '$message $exclamation';
    }
    print(message);
}

In this example, the exclamation parameter is optional. When calling the greet function, we can omit the exclamation parameter:

greet('Alice', 'Hello'); // Output: Hello, Alice


Or, we can include it:

greet('Bob', 'Hi', '!'); // Output: Hi, Bob!


Named Parameters


Dart allows you to specify named parameters for your functions. When you define named parameters, you can specify a default value for each of them. The syntax for specifying named parameters is as follows:

function_name({named_parameter1: default_value1, named_parameter2: default_value2, …, named_parameterN: default_valueN}) { … }

When calling a function with named parameters, you can specify the values for those parameters by using the parameter name followed by a colon and the value. You can provide any number of named parameters in any order. Here’s an example:

void printPersonDetails({String name, int age, String address}) {
    print("Name: $name");
    print("Age: $age");
    print("Address: $address");
}
void main() {
// Using named parameters
    printPersonDetails(name: "John", age: 30, address: "123 Main St");
    printPersonDetails(age: 25, name: "Jane");
    printPersonDetails(address: "456 Elm St", name: "Bob", age: 40);
}


In the above code, we define a function called printPersonDetails that takes three named parameters: name, age, and address. We can call this function using any combination of named parameters, in any order.

Optional Parameters


Dart also allows you to specify optional parameters for your functions. Optional parameters are parameters that don’t need to be specified when calling the function. There are two types of optional parameters in Dart: positional and named.

Positional optional parameters are specified using square brackets ([]). Here’s an example:

void printNumbers(int a, [int b, int c]) {
    print("a = $a");
    if (b != null) print("b = $b");
    if (c != null) print("c = $c");
}

void main() {
    printNumbers(1);
    printNumbers(2, 3);
    printNumbers(4, 5, 6);
}


In the above code, we define a function called printNumbers that takes three optional parameters: b and c. We can call this function with any number of arguments, and if an optional parameter is not specified, its value will be null.

Named optional parameters are specified using curly braces ({}). Here’s an example:

void printPersonDetails(String name, {int age, String address}) {
    print("Name: $name");
   if (age != null) print("Age: $age");
    if (address != null) print("Address: $address");
}

void main() {
    printPersonDetails("John");
    printPersonDetails("Jane", age: 25);
    printPersonDetails("Bob", age: 40, address: "456 Elm St");
}


In the above code, we define a function called printPersonDetails that takes two named optional parameters: age and address. We can call this function with any combination of named optional parameters, and if a parameter is not specified, its value will be null.

Lambda Functions


In Dart, we can define Lambda functions or anonymous functions, which do not have any name. Lambda functions are useful when you want to pass a small function as a parameter to a higher-order function or when you want to create a function on the fly.

Dart also supports lambda functions, also known as anonymous functions or closures. Lambda functions are functions that don’t have a name, and can be defined on the fly. Here’s an example:

void main() {
// Defining a lambda function
    var square = (int x) => x * x;
    print(square(2)); // Output: 4
    print(square(3)); // Output: 9
}

Lambda functions are defined using the following syntax:

(parameter-list) { function-body }

Here, the parameter list is a comma-separated list of parameters, and the function body is the code that performs the function’s operation. The function body can be a single expression or a block of statements enclosed in curly braces.

Here is an example of a lambda function that takes two integer arguments and returns their sum:

void main() {
    Function add = (int a, int b) => a + b;
    print(add(2, 3));
}


In the above example, we define a lambda function using the Function keyword, which takes two integer parameters and returns their sum. We then call the function by passing two integer arguments to it and print the result.

Lambda functions are often used with higher-order functions, which are functions that take one or more functions as arguments or return a function as a result.

Example:

void main() {
    var list = [1, 2, 3, 4, 5];
    // Using Lambda function with forEach() method
    list.forEach((item) => print(item * 2));
}


In the above example, we have a list of integers, and we want to print each element of the list multiplied by 2. We achieve this by using the forEach() method, which takes a lambda function that performs an operation on each element of the list.

Lambda functions are a powerful feature of Dart that allows us to create anonymous functions on the fly. They are particularly useful when working with higher-order functions or when we need to pass a small function as a parameter to another function.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.

Other Recommended Article